在上一节, 我们认识了View与Controller, 通过在Controller中定义的变量, 把变量的值传入到View中, 成功生成了动态的页面。但要真正生成一个动态展示内容的页面, 还需要将数据库中的数据取出来。
这就需要用到Model层了
建立数据库与表
在mysql中建立一个phalcon_blog数据库, 并生成下面两张表:
CREATE TABLE `articles` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '',
`content` text,
`user_id` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
注意: id是表的主键, 表名_id则是其他表的主键
我们可以随意插入两条数据
数据库配置
在app/config/config.php中, 在database中填入数据库的配置信息, 这样Phalcon与数据库的联系就建立好了
return new \Phalcon\Config([
'database' => [
'adapter' => 'Mysql',
'host' => 'localhost',
'username' => 'root',
'password' => 'passowrd',
'dbname' => 'phalcon_blog',
'charset' => 'utf8',
],
'application' => [
'appDir' => APP_PATH . '/',
'controllersDir' => APP_PATH . '/controllers/',
'modelsDir' => APP_PATH . '/models/',
'migrationsDir' => APP_PATH . '/migrations/',
'viewsDir' => APP_PATH . '/views/',
'pluginsDir' => APP_PATH . '/plugins/',
'libraryDir' => APP_PATH . '/library/',
'cacheDir' => BASE_PATH . '/cache/',
'baseUri' => '/new_phalcon/',
]
]);
建立Model
要将Model与表对应起来也非常容易, 使用如下命令即可
$phalcon model articles
Phalcon Tools会为我们生成app/models/Articles.php这个文件:
class Articles extends \Phalcon\Mvc\Model
{
public $id;
public $title;
public $content;
public $user_id;
public $created_at;
public $updated_at;
public function getSource()
{
return 'articles';
}
}
可以看到, articles中的字段都生成了相应Articles的属性。也就是说, 表的每条数据, 都会经过Model转化成一个对象。Cool~
从Controller中取出数据
我们修改一下app/controllers/ArticlesController:
class ArticlesController extends ControllerBase
{
public function indexAction()
{
$this->view->article = Articles:find(1);
}
}
Articles:find(1) 会为我们取出id为1的数据, 并转化为对象
修改View
然后我们修改app/views/articles/index.volt:
First Blog
{{ article.title }}
打开浏览器localhost:8008/articles, Amazing~
小结
我们在Controller中, 通过Model取出了数据, 并将数据传给View
这样一个V - C - M 之间的关系贯穿于整个MVC架构的使用