在上一節(jié), 我們認識了View
與Controller
, 通過在Controller
中定義的變量, 把變量的值傳入到View
中, 成功生成了動態(tài)的頁面砰左。但要真正生成一個動態(tài)展示內容的頁面, 還需要將數據庫中的數據取出來拢蛋。
這就需要用到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
:
<h3>First Blog</h3>
<p>{{ article.title }}</p>
打開瀏覽器localhost:8008/articles
, Amazing~
小結
我們在Controller
中, 通過Model
取出了數據, 并將數據傳給View
這樣一個V - C - M
之間的關系貫穿于整個MVC
架構的使用