通过上面的讲解,了解了命名空间,路径别名,开发流程和开发规范以及mvc开发最佳实际,你应该对接下来的工作又爱有恨,因为作为码农,model层的代码是你的骄傲,你的大半辈子的编码工作都在这里进行。
让我们了解yii的Model的基本规则和使用方法,揭开yii的model的神秘面纱,从此悲喜交加。终于又可以贴代码啦。
/////////////////////////////////////////////////////////
模型
模型是 CModel 或其子类的实例。模型用于保持数据以及与其相关的业务逻辑。
模型是单独的数据对象。它可以是数据表中的一行,或者一个用户输入的表单。 数据对象的每个字段对应模型中的一个属性。每个属性有一个标签(label), 并且可以通过一系列规则进行验证。
Yii 实现了两种类型的模型:表单模型和 Active Record。二者均继承于相同的基类 CModel。
表单模型是 CFormModel 的实例。表单模型用于保持从用户的输入获取的数据。 这些数据经常被获取,使用,然后丢弃。例如,在一个登录页面中, 我们可以使用表单模型用于表示由最终用户提供的用户名和密码信息。更多详情,请参考 使用表单。
Active Record (AR) 是一种用于通过面向对象的风格抽象化数据库访问的设计模式。 每个 AR 对象是一个CActiveRecord 或其子类的实例。代表数据表中的一行。 行中的字段对应 AR 对象中的属性。更多关于 AR 的细节请阅读 Active Record.
基本的定义规则:
1.存放位置:
一般情况在/yii_dev/testwebap/protected/models
如果有modules在例如/yii_dev/testwebap/protected/modules/testmod/models
2.命名规则
│ ├── migrations
│ ├── models
│ │ ├── ContactForm.php
│ │ ├── LoginForm.php
│ │ └── User.php
│ ├── modules
文件名大写开头,通风风格,标准的类名格式
通常类名和文件名相同。
类要集成或间接集成CModel。
如果是普通的模型类继承CModel
如果是涉及到Form的模型要继承CFormModel。类名、文件名以Form结尾
如果是涉及到数据库的模型要继承CActiveRecord。
3.使用方法。根据以前的知识我们知道应该是在controller中实例化然后使用。但是为了让controller个简单,可能需要创建更多的model类处理逻辑,然后在controller中实例化,使用,使用。总之在controller实例化,但又要让controller保持简单。所以。。。
form model的使用方法
SiteController.php
/** * Displays the contact page */ public function actionContact() { $model=new ContactForm; if(isset($_POST['ContactForm'])) { $model->attributes=$_POST['ContactForm']; if($model->validate()) { $headers="From: {$model->email}rnReply-To: {$model->email}"; mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers); Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.'); $this->refresh(); } } $this->render('contact',array('model'=>$model)); }
数据库model的使用方法
UserController.php
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new User; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['User'])) { $model->attributes=$_POST['User']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('create',array( 'model'=>$model, )); }
应该对使用有个了解了。
下面罗列几个demos的model的定义实例,代码都是以前yii给自动生成的。也是学习的第一手资料,更是最标准的第一手资料。可能会看到好多方法,让自己写的时候可能无从下手。接下来的文章将慢慢讲这些model的定义,以及一些细微的写法。这里先了解代码,大概看看,需要学些什么。
'Remember me next time', ); } /** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ public function authenticate($attribute,$params) { if(!$this->hasErrors()) { $this->_identity=new UserIdentity($this->username,$this->password); if(!$this->_identity->authenticate()) $this->addError('password','Incorrect username or password.'); } } /** * Logs in the user using the given username and password in the model. * @return boolean whether login is successful */ public function login() { if($this->_identity===null) { $this->_identity=new UserIdentity($this->username,$this->password); $this->_identity->authenticate(); } if($this->_identity->errorCode===UserIdentity::ERROR_NONE) { $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days Yii::app()->user->login($this->_identity,$duration); return true; } else return false; } }
128), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, username, password, email', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'Id', 'username' => 'Username', 'password' => 'Password', 'email' => 'Email', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('username',$this->username,true); $criteria->compare('password',$this->password,true); $criteria->compare('email',$this->email,true); return new CActiveDataProvider('User', array( 'criteria'=>$criteria, )); } }
总结一下YII中Model通常是什么样子:
1.具备属性来存储数据。
2.public function rules()用来定义验证规则
rules()
返回的每个规则必须是以下格式:
array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...附加选项)
其中 AttributeList(特性列表)
是需要通过此规则验证的特性列表字符串,每个特性名字由逗号分隔;Validator(验证器)
指定要执行验证的种类;on
参数是可选的,它指定此规则应被应用到的场景列表;
附加选项是一个名值对数组,用于初始化相应验证器的属性值。
声明属性对于的标签名称
例如
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
上面具体的细节使用后续讲解。