Yii Model概述与数据库配置
本实例深入解析了Yii框架中Model(模型)的具体创建流程与应用技巧,旨在为开发者提供实用的参考指南。
Yii框架主要实现了两类模型:表单模型(CFormModel类)与活动记录模型(CActiveRecord类),二者均派生自基类CModel。CFormModel主要用于封装从HTML表单收集的输入数据,涵盖验证逻辑及其他业务规则,其数据可暂存于内存或通过Active Record持久化至数据库。
数据库连接配置
需在config/main.php配置文件中进行设置
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=oss',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'hahaha',
'charset' => 'utf8',
//表前缀
'tablePrefix'=>"oss_"
),
确保启用PDO扩展以支持数据库操作
查看SQL执行日志
//显示日志信息,包括sql的查询信息
array(
'class'=>'CWebLogRoute',
),
开启相关注释以启用日志功能
基于CActiveRecord的Model实现
一、基于CActiveRecord的Model实现
Active Record(AR)是一种面向对象的设计模式,用于抽象化数据访问。在Yii中,每个AR对象实例均为CActiveRecord类或其子类。它将数据库表中的一行记录映射为一个对象,封装了底层数据库细节及大部分业务逻辑。表中每列对应AR对象的一个属性,实现了表到类、行到对象、列到属性的映射。除了简单的映射关系,AR还负责处理所有对数据库的读写操作及相关业务逻辑。
1) 声明基于CActiveRecord类的Model
class Post extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return '{{post}}';
}
public function primaryKey()
{
return 'id';
// return array('pk1', 'pk2');
}
}
2) 利用父类方法执行数据库操作
(1) 插入操作:
$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();
(2) 查询操作: 常用几种方法
// find the first row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with the specified primary key
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attribute values
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// find the first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);
$criteria=new CDbCriteria;
$criteria->select='title'; // only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria);
$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID=:postID',
'params'=>array(':postID'=>10),
));
// find all rows satisfying the specified condition
$posts=Post::model()->findAll($condition,$params);
// find all rows with the specified primary keys
$posts=Post::model()->findAllByPk($postIDs,$condition,$params);
// find all rows with the specified attribute values
$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);
// find all rows using the specified SQL statement
$posts=Post::model()->findAllBySql($sql,$params);
// get the number of rows satisfying the specified condition
$n=Post::model()->count($condition,$params);
// get the number of rows using the specified SQL statement
$n=Post::model()->countBySql($sql,$params);
// check if there is at least a row satisfying the specified condition
$exists=Post::model()->exists($condition,$params);
(3) 更新操作
// update the rows matching the specified condition
Post::model()->updateAll($attributes,$condition,$params);
// update the rows matching the specified condition and primary key(s)
Post::model()->updateByPk($pk,$attributes,$condition,$params);
// update counter columns in the rows satisfying the specified conditions
Post::model()->updateCounters($counters,$condition,$params);
(4) 删除操作
$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$post->delete();
// delete the rows matching the specified condition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specified condition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);
(5) 事务处理
$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
// find and save are two steps which may be intervened by another request
// we therefore use a transaction to ensure consistency and integrity
$post=$model->findByPk(10);
$post->title='new post title';
$post->save();
$transaction->commit();
}
catch(Exception $e)
{
$transaction->rollBack();
}
基于CFormModel的Model实现
二、基于CFormModel的Model实现
在编写HTML表单之前,需明确用户输入的数据类型及校验规则。模型类在此过程中起到核心作用,用于存储用户输入并执行验证逻辑。
根据数据处理方式的不同,可创建两种模型:若数据仅用于临时处理或验证后丢弃,应使用表单模型(form model);若数据需持久化至数据库,则使用活动记录(active record)。两者均继承自CModel,共享通用的表单接口。
1) 模型类的定义
以下示例创建一个LoginForm模型,用于收集登录页面的用户输入。由于登录信息仅用于身份验证而无需保存,故采用form model形式构建。
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
}
LoginForm定义了三个属性(attributes):$username、$password和$rememberMe。
这些属性分别用于记录用户名、密码及“记住登录”选项。其中$rememberMe默认值为false,因此表单渲染时复选框默认未勾选。
提示:此处使用术语"attributes"而非"properties",以区别于普通类属性。
2) 声明验证规则
将用户提交的数据填充至模型后,使用前需验证其合法性。这通过rules()方法配置验证规则数组来实现。
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
private $_identity;
public function rules()
{
return array(
array('username, password','required'),
array('rememberMe', 'boolean'),
array('password', 'authenticate'),
);
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors()) // we only want to authenticate when no input errors
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect password.');
}
}
}
上述代码规定用户名和密码为必填项,密码需经过特定验证,且rememberMe必须为布尔类型。
rules()返回的每条规则需遵循特定格式。
array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...附加选项)
AttributeList为由逗号分隔的需要验证的属性名列表;Validator指定验证类型;可选的on参数指定规则适用的场景列表;附加选项用于初始化验证器的相关属性。
在规则中指定Validator有三种方式:首先,Validator可以是类的一个方法,如authenticate。该方法需按如下格式声明: 复制代码 代码如下:public function ValidatorName($attribute,$params) { ... } 其次,Validator可以是验证器类的类名。当规则适用时,系统会创建该验证器类的实例进行实际验证。规则中的附加属性用于初始化实例。验证器类必须继承自CValidator。
提示:在为Active Record模型指定规则时,可使用特殊参数'on'。
该参数值可为'insert'或'update',使规则仅在插入或更新时生效。若未声明,规则将在任何调用save()时生效。
第三,Validator可以是预定义的验证器别名。例如前述例子中的"required"即为CRequiredValidator的别名,用于验证属性非空。以下是预定义验证器别名的列表:
? boolean:CBooleanValidator的别名,验证属性值是否为CBooleanValidator::trueValue或CBooleanValidator::falseValue ? captcha:CCaptchaValidator的别名,验证属性值是否与CAPTCHA显示的验证码相等 ? compare:CCompareValidator的别名,验证属性值是否等于另一属性或常量 ? email:CEmailValidator的别名,验证属性值是否为合法的email地址 ? default:CDefaultValueValidator的别名,为属性指派默认值 ? exist:CExistValidator的别名,验证属性值是否在表的列中存在 ? file: CFileValidator的别名,验证属性是否包含上传文件名 ? filter:CFilterValidator的别名,使用过滤器转换属性形式 ? in: CRangeValidator的别名,验证属性值是否在预定值列表中 ? length: CStringValidator的别名,确保属性值长度在指定范围内 ? match: CRegularExpressionValidator的别名,验证属性是否匹配正则表达式 ? numerical: CNumberValidator的别名,验证属性是否为有效数字 ? required: CRequiredValidator的别名,验证属性值是否非空 ? type: CTypeValidator的别名,验证属性是否为指定数据类型 ? unique: CUniqueValidator的别名,验证属性在数据表字段中是否唯一 ? url: CUrlValidator的别名,验证属性是否为有效的URL路径.
下面给出一些使用预定义验证器的示例。
// username is required
array('username', 'required'),
// username must be between 3 and 12 characters
array('username', 'length', 'min'=>3, 'max'=>12),
// when in register scenario, password must match password2
array('password', 'compare', 'compareAttribute'=>'password2',
'on'=>'register'),
// when in login scenario, password must be authenticated
array('password', 'authenticate', 'on'=>'login'),
3) 安全属性的设置
模型创建后,通常需根据用户输入填充属性。可通过批量赋值便捷实现。
$model=new LoginForm;
if(isset($_POST['LoginForm']))
$model->attributes=$_POST['LoginForm'];
最后一行语句即为批量赋值,将$_POST['LoginForm']中的各属性值赋给模型对应属性,其等价于以下语句:
foreach($_POST['LoginForm'] as $name=>$value)
{
if($name is a safe attribute)
$model->$name=$value;
}
确定哪些属性为安全属性至关重要。例如,若将数据表主键暴露为安全属性,攻击者可能通过修改主键值来访问无权限管理的数据。
4) 1.1版中的安全属性机制
在1.1版本中,若属性在适用的规则中指定了验证器,则该属性被视为安全的。例如:
array('username, password', 'required', 'on'=>'login, register'),
array('email', 'required', 'on'=>'register'),
上述代码中,用户名和密码在login场景下不允许为空;用户名、密码和邮箱在register场景下不允许为空。因此,若在login场景下进行批量赋值,仅用户名和密码会被赋值,因为login场景的规则中仅涉及这两个属性;而在register场景下,这三个属性均会被赋值。
// in login scenario
$model=new User('login');
if(isset($_POST['User']))
$model->attributes=$_POST['User'];
// in register scenario
$model=new User('register');
if(isset($_POST['User']))
$model->attributes=$_POST['User'];
为何采用此策略判断属性安全性?因为若属性已有校验规则,我们便无需过度担忧。
需注意的是,验证器旨在检测用户输入的数据,而非代码生成的数据(如时间戳、自增主键等)。因此,勿为无需用户输入的属添加验证器。
有时需声明某些属性为安全属性,但不必指定具体验证规则。例如文章正文属性,允许用户任意输入。为此,可使用safe规则。 复制代码 代码如下:array('content', 'safe')
相应地,也有unsafe规则用于指定不安全属性。 复制代码 代码如下:array('permission', 'unsafe') unsafe规则不常用,通常作为以前定义的安全属性的例外情况存在。 5) 获取验证错误 验证结束后,所有可能的错误均存储在模型实例中。可通过调用CModel::getErrors()和CModel::getError()重新获取。前者返回指定模型属性的所有错误,后者仅返回第一条错误。
6) 属性标签
设计表单时,需为用户输入框显示标签以提示输入。虽可在form中硬编码,但在模型中指定更为灵活方便。
默认情况下,CModel直接返回属性名作为标签。可通过重写attributeLabels()方法来自定义。后续章节将展示,在模型中指定标签能更高效、强大地进行表单构建。
希望本文所述内容能对基于Yii框架的PHP程序设计有所帮助。