Create and use Model in Yii _ php instance

Source: Internet
Author: User
Tags valid email address
This article mainly introduces how to create and use a Model in Yii, and analyzes in detail the basic creation techniques, usage methods, and related Precautions of the Model in Yii Based on the instance form, for more information about how to create and use a Model in Yii, see the following example. We will share this with you for your reference. The details are as follows:

YII implements two models: Form Model (CFormModel class) and Active Record model (lateral verecord class). They all inherit from the CModel class. CFormModel indicates that the data model is input collected from HTML forms and encapsulates all logic (such as form verification and other business logic, applied to form fields ). It can store data in internal storage, or store data in a database with the help of an Active Record.

Database Connection operations

In config/main. php

'Db' => array ('ononstring' => 'mysql: host = localhost; dbname = Oss', 'default' repare' => true, 'username' => 'root ', 'Password' => 'hahaha', 'charset' => 'utf8', // table prefix 'tableprefix' => "oss _"),

Open comments. php must support pdo.

View operation logs

// Display the log information, including the SQL query information array ('class' => 'cweblogroute ',),

Open comments

1. Model Based on CActiveRecord

Active Record (AR) is a design pattern that uses object-oriented abstraction to access data. In Yii, each AR object instance can be a CActiveRecord class or its subclass. It encapsulates a row of records in a database table or view, and encapsulates all the logic and information details of the database. Most of the business logic must use this model. The values of each column in a row in the database table correspond to a property of the AR object. It maps tables to classes, rows to objects, and columns to object data. That is to say, each instance of the Active Record class represents a row of tables in the database. However, an Active Record class is not only a ing between fields in the database table and attributes in the class. It also needs to process some business logic on the data and define all read/write operations on the database.

1) declare a Model based on the CActiveRecord class

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) use the parent class method to complete database operations

(1) Insert:

$post=new Post;$post->title='sample post';$post->content='content for the sample post';$post->create_time=time();$post->save();

(2) Select: several common methods

// 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

// update the rows matching the specified conditionPost::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 conditionsPost::model()->updateCounters($counters,$condition,$params);

(4) Delete

$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10$post->delete();// delete the rows matching the specified conditionPost::model()->deleteAll($condition,$params);// delete the rows matching the specified condition and primary key(s)Post::model()->deleteByPk($pk,$condition,$params);

(5) Use transactions

$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();}

2. Model Based on CFormModel

Before writing the HTML required for a form, we need to determine what data we want the user to input and what rules should be met. A model class can be used to record this information. A model is the core of user input and verification.

Based on how we use user input, we can create two types of models. If the input data is collected, used, and discarded, a form model is created. If the input data is saved to the database, we will use active record. Both models inherit the common interfaces of forms defined in their same base class CModel.

1) Model class definition

In the following example, A LoginForm model is created to collect user input on the login page. Because the login information is only used for user authentication and does not need to be saved, we use form model to create

class LoginForm extends CFormModel{public $username;public $password;public $rememberMe=false;}

LoginForm declares three attributes (attributes), $ username, $ password, and $ rememberMe.

Used to record the user name, password, and logging options entered by the user. Because the default value of $ rememberMe is false, the corresponding selection box is not checked when the form is displayed.

Tip: we use the name "attributes" instead of "properties" to distinguish them from normal properties.

2) Declare verification rules

Once the data submitted by the user is filled into the model, we need to check whether the data is valid before use. This is achieved through a set of rules for the input. In the rulers () method, we configure an array to define verification 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.');}}}

The code above indicates that the user name and password must be verified, and the password must be a Boolean rememberMe.

Each rule returned by rules () must follow the following format:

Array ('butbutelist', 'validator', 'on' => 'scenariolist',... additional options (additional options ))

AttributeList is a list of attribute names to be verified separated by commas. Validator points out what verification is required. The optional on parameter specifies the Application Scenario list of the rule. (additional options) is the corresponding name-value, which is used to initially correspond to the relevant attributes of the validators.

There are three methods to specify Validator in a rule. First, Validator can make a method of this class, such as authenticate in the above example. The Validator method must be declared in the following format:

The Code is as follows:

Public function ValidatorName ($ attribute, $ params ){...}


Second, Validator enables the Class Name of the validators. When the rules apply, an instance of the validators class will be created and verified. The additional attributes in the rule, used for the attributes of the initial instance. The validators class must inherit from CValidator

Tip: when specifying rules for the active record model, we can use the special parameter 'on ',

This parameter can be set to 'insert' or 'update', which can be applied when the rule is inserted or updated. If no life exists, this rule applies when saving () is called.

Third, Validator can pre-define the alias of the validators class. In the preceding example, "required" is the alias of CRequiredValidator. It is used to verify that the attribute cannot be blank. The following is a list of predefined authenticator category names.

? Boolean: the alias of CBooleanValidator to verify whether the attribute value is CBooleanValidator: trueValue or CBooleanValidator: falseValue
? Captcha: the alias of CCaptchaValidator. Verify that the attribute value is equal to the value of the verification code displayed in CAPTCHA.
? Compare: the alias of CCompareValidator to verify whether the attribute value is equal to another attribute or a constant.
? Email: the alias of CEmailValidator to verify whether the attribute value is a valid email address.
? Default: the alias of cdefavaluvaluevalidator. a default value is assigned to the property.
? Exist: the alias of CExistValidator to verify whether the attribute value can be found in the column of the table.
? File: the alias of CFileValidator to verify whether the attribute contains the name of the uploaded file.
? Filter: the alias of CFilterValidator. A filter is used to convert attributes.
? In: the alias of CRangeValidator to verify whether the attribute value is in a reserved value list.
? Length: the alias of CStringValidator to ensure that the length of the attribute value is within the specified range.
? Match: the alias of CRegularExpressionValidator to verify whether the attribute matches a regular expression.
? Numerical: the alias of CNumberValidator to verify whether the attribute is a valid number.
? Required: the alias of CRequiredValidator to verify whether the attribute value is null.
? Type: the alias of CTypeValidator to verify whether the attribute is of the specified data type.
? Unique: the alias of CUniqueValidator to verify whether the attribute is unique in the data table field.
? Url: the alias of CUrlValidator to verify whether the attribute is a valid URL path.

Here are some examples of using the predefined validators.

// username is requiredarray('username', 'required'),// username must be between 3 and 12 charactersarray('username', 'length', 'min'=>3, 'max'=>12),// when in register scenario, password must match password2array('password', 'compare', 'compareAttribute'=>'password2','on'=>'register'),// when in login scenario, password must be authenticatedarray('password', 'authenticate', 'on'=>'login'),

3) Security attribute settings

After a model is created, we often need to fill in attributes for it based on the user input. This can be easily achieved through the batch Assignment Method below

$model=new LoginForm;if(isset($_POST['LoginForm']))$model->attributes=$_POST['LoginForm'];

The last statement is batch assignment. Each attribute in $ _ POST ['loginform'] is assigned to the corresponding model attribute, which is equivalent to the following statement.

foreach($_POST['LoginForm'] as $name=>$value){if($name is a safe attribute)$model->$name=$value;}

Declaring whether an attribute is a security attribute is crucial. For example, if I expose the primary key of a data table as a security attribute, I can modify the value of the primary key to manage data that has no permission to manage and launch attacks.

4) security attributes in version 1.1

In Version 1.1, if the property is specified in the applicable rule, it is considered safe. For example

array('username, password', 'required', 'on'=>'login, register'),array('email', 'required', 'on'=>'register'),

The username and password attributes in the above Code cannot be blank in the login scenario. The username and password cannot be blank in the register scenario. Therefore, if you perform batch assignment in the login scenario, only the user name and password will be assigned a value, because only these two attributes appear in the verification rules in the login scenario, however, in the register scenario, all three attributes are assigned values.

// 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'];

So why do we use such a policy to determine whether an attribute is a security attribute? Because one attribute already has one or more validation rules, do I have to worry about it?

It should be noted that the validators are used to detect user input data, rather than data generated by code (such as timestamps and auto-incrementing primary keys ). Therefore, do not add validators for attributes that do not require user input.

Sometimes we want to declare some attributes as security attributes, but we do not need to specify a verification rule. For example, the text attribute of an article allows any user input. To achieve this goal, we can use safe rules.

The Code is as follows:

Array ('content', 'safe ')

There is also an unsafe rule to specify which attributes are insecure.

The Code is as follows:

Array ('permission', 'unsafe ')


Unsafe is not commonly used. This is an exception for the security attributes you previously defined.
5) Get verification error
When verification is completed, any possible errors are stored in the model instance. We can call CModel: getErrors () and CModel: getError () to obtain it again. The difference between the two methods is that the first method can return all errors of the specified model attribute, while the second method only returns the first error.

6) attribute tag

When designing a form, we need to display a label for the user input box to prompt the user to enter. Although we can write it in form again, it is more convenient and flexible if we specify it in the corresponding model.

By default, CModel simply returns the attribute name as a tag. This can be customized by overwriting attributeLabels. In the following sections, we will see that specifying tags in the model allows us to create a form more quickly and more efficiently.

I hope this article will help you design php programs based on the yii framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.