## 2.5 模型类
~~~
1. 创建一个模型类
2. 访问模型
3. 模型访问数据,并打印
~~~
### 1. 创建一个模型类
*D:\wamp\www\web.com\core\lib\model.php*
~~~
<?php
namespace core\lib;
class model extends \PDO
{
public function __construct()
{
$dsn = 'mysql:host=localhost;dbname=demo;charset=UTF8;';
$username = 'root';
$password = 'root';
try {
parent::__construct($dsn, $username, $password);
} catch (\Exception $e) {
p($e->getMessage());
die;
}
}
}
~~~
### 2. 访问模型
*D:\wamp\www\web.com\app\ctrl\indexCtrl.php*
~~~
<?php
namespace app\ctrl;
class indexCtrl
{
public function index()
{
$model = new \core\lib\model();
$sql = "SELECT * FROM `cat`";
p($model->query($sql));
}
}
~~~
### 3. 模型访问数据,并打印
~~~
<?php
namespace app\ctrl;
class indexCtrl
{
public function index()
{
$model = new \core\lib\model();
$sql = "SELECT * FROM `cat`";
$ret = $model->query($sql);
p($ret);
// foreach ($model->query($sql) as $key => $value) {
// p($value);
// }
p($ret->fetchAll());
}
}
~~~
> 备注:PDOStatement <http://php.net/manual/zh/class.pdostatement.php>
### 效果如图
![](https://box.kancloud.cn/63c0d569574b4f7c006989c429832e86_742x728.png)