在这之前,你已经下载了Solar系统,创建了工作区并做了一些配置。接下来,我们将创建数据表,并创建与之对应的模型。
-
在数据库中创建blogs表
-- SQLite CREATE TABLE blogs ( id INTEGER PRIMARY KEY AUTOINCREMENT, created TIMESTAMP DEFAULT NULL, updated TIMESTAMP DEFAULT NULL, status VARCHAR(15), title VARCHAR(63) NOT NULL, body CLOB ); -- MySQL CREATE TABLE blogs ( id INTEGER AUTO_INCREMENT PRIMARY KEY, created DATETIME DEFAULT NULL, updated DATETIME DEFAULT NULL, status VARCHAR(15), title VARCHAR(63) NOT NULL, body TEXT ); -- PostgreSQL CREATE TABLE blogs ( id SERIAL PRIMARY KEY, created TIMESTAMP DEFAULT NULL, updated TIMESTAMP DEFAULT NULL, status VARCHAR(15), title VARCHAR(63) NOT NULL, body LONGTEXT );
Note 如果你使用SQLite,那么你需要给web服务器权限去读写数据库。
-
现在我们已经创建了一张表,接下来在表中添加原生的数据以便后面有数据可操作。
INSERT INTO blogs (created, updated, status, title, body) VALUES ( '2010-01-01 00:00:00', '2010-01-01 00:00:00', 'public', 'Public Blog Entry', 'First post!' ); INSERT INTO blogs (created, updated, status, title, body) VALUES ( '2010-01-01 06:00:00', '2010-01-01 06:00:00', 'draft', 'A Draft Article', 'My, it sure is drafty in here.' ); INSERT INTO blogs (created, updated, status, title, body) VALUES ( '2010-01-01 12:00:00', '2010-01-01 12:00:00', 'draft', 'Please delete me', 'This is here to be deleted.' );
-
切换至命令行环境,进入SYSTEM目录,使用make-model命令,你将会看到类似下面这种动作:
$ ./script/solar make-model Acme_Model_Blogs Making model 'Acme_Model_Blogs'. Will write to 'SYSTEM/include/'. Making model 'Acme_Model_Blogs'. Will write to '/Users/pmjones/Sites/blog-demo/include/'. Using table 'blogs'. Not using inheritance. Making class directory ... done. Writing model class ... done. Writing record class ... done. Writing collection class ... done. Connecting to database for metadata ...connected. Fetching table cols ... done. Fetching index info ... no indexes found. Writing metadata class ... done. Creating locale directory ... done. Saving locale file for en_US ... done. $
Note 这里发生了什么?Solar接收通过make-model传递的参数,使用最后一个下划线之后的部分作为表名,接着Solar会在数据库中查找该表并创建模型定义、记录类、查询类、列和索引信息及本地化字符文件。
-
对于基本的字段验证(例如:NOT NULL字段在保存之前不能为空),Solar模型处理得相当好。但是,这可能不够,我们通常还需要在模型数据上加上额外的验证条件。下面我们来改变status字段的验证条件,约束其必须在某个集合或列表中取值。
打开SYSTEM/source/acme/Acme/Model/Blogs.php文件,编辑_setup()方法,为status字段添加一个过滤器。
<?php protected function _setup() { // chain to parent parent::_setup(); // add a validation filter on the status column $this->_addFilter('status', 'validateInList', array( 'draft', 'public', )); }
Note Solar中有很多关于验证和审查数据的过滤器。具体可参考Solar_Filter包。