Modeling (model) creation and use in Yii, Yiimodel
In this paper, we analyze the creation and use of model (models) in Yii. Share to everyone for your reference, as follows:
YII implements two models, the form model (Cformmodel Class) and the active record model (Cativerecord Class), which inherit from the Cmodel class. The data model represented by Cformmodel is an input collected from an HTML form, encapsulating all the logic (such as validation of forms and other business logic, applied to the domain of the form). It can store the data in memory or, with the help of an active record, into the database.
Database connection Operations
In the config/main.php
' DB ' =>array ( ' connectionString ' = ' mysql:host=localhost;dbname=oss ', ' emulateprepare ' + = True, ' username ' = ' root ', ' password ' = ' hahaha ', ' charset ' = ' utf8 ', //Table prefix ' tableprefix ' = "Oss_"),
Open comments, PHP to support PDO
View the Operations log
Displays log information, including query information for SQL Array ( ' class ' = ' Cweblogroute ',),
Open a Comment
I. Model based on the Cactiverecord
An Active Record (AR) is a design pattern that abstracts access data in an object-oriented manner, and each instance of an AR object can be a Cactiverecord class or its subclass in Yii. It wraps a row of records in a database table or view, encapsulates the details of all the logical and hearsay databases, and has most of the business logic that must be used in this model. The value of each column field in a row of a database table corresponds to an attribute of the AR object. It maps tables to classes, rows to objects, and columns to data for objects. This means that each instance of an active record class represents a row of tables in the database. However, an Active record class is not just a mapping between a field in a database table and a property in a class. It also needs to process some business logic on the data, which defines all read and write operations to 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 the database operation
(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 methods commonly used
Find the first row satisfying the specified Condition$post=post::model ()->find ($condition, $params);//Find the row W ITH 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=:p ostid '; $criteria->params=array (':p ostid ' = $post =post::model ()->find ($criteria), $post =post::model ()->find (Array (' SELECT ' = ' title ', ' Condition ' = ' postid=:p ostid ', ' params ' =>array (':p ostid ' =>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 the 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::mode L ()->deleteall ($condition, $params);//delete the rows matching the specified condition and primary key (s) Post::model ( )->DELETEBYPK ($PK, $condition, $params);
(5) Using transactions
$model =post::model (); $transaction = $model->dbconnection->begintransaction (); try{//find and save are both steps Which May is intervened by another request//we therefore use a transaction to ensure consistency and integrity$post= $mode L->FINDBYPK, $post->title= ' new post title '; $post->save (); $transaction->commit ();} catch (Exception $e) {$transaction->rollback ();}
Two. Model based on the Cformmodel
Before we write the HTML required for the form, we need to decide what data we want the user to enter and what rules we should conform to. A model class can be used to record this information, and the model is the core of keeping the user input and validating
Depending on how we use the user's input, we can create two types of models. If the user input data is collected, used, and then discarded, we will create a form model, and if the data entered by the user is saved to the database, we will use the active record. Both models inherit the common interface of the form defined in their same base class Cmodel.
1) Definition of model class
In the following example, we create a loginform model that collects the input of the user on the landing page. Since the login information is only for user authentication and does not need to be saved, we use the form model to create
Class LoginForm extends Cformmodel{public $username;p ublic $password;p ublic $rememberMe =false;}
LoginForm altogether declared three attributes (attributes), $username, $password, $rememberMe
Used to record user-entered user names, passwords, and whether to remember the login option. Because $rememberme has a default value of FALSE, the corresponding marquee is not checked when the form is displayed.
Tip: We use the name "attributes" instead of "properties" to differentiate them from the normal attributes (properties).
2) declaring validation rules
Once the user submits the data to the model, we have to check whether they are legal before use. This is achieved by a set of rules validation for the input. We define validation rules in the rulers () method by configuring an array
Class LoginForm extends Cformmodel{public $username;p ublic $password;p ublic $rememberMe =false;private $_identity; Public Function rules () {return Array (' username, password ', ' required '), Array (' RememberMe ', ' Boolean '), Array (' Password ', ' Authenticate '),);} Public function Authenticate ($attribute, $params) {if (! $this->haserrors ())//We are 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 above code indicates that the user name and password are required, the password needs to be verified, and the RememberMe must be Boolean
Each rule returned in rules () must be in the following format
Array (' AttributeList ', ' Validator ', ' on ' = ' scenariolist ', ... Additional option (additional options))
AttributeList is a comma-delimited list of attribute names that need to be validated. Validator points out what needs to be verified. The optional on parameter indicates the list of scenarios that the rule applies to, and (additional options) is the corresponding name-value for the relevant properties of the initial corresponding validator
There are three ways to specify validator in a rule, first validator can make a method of the class, such as the authenticate in the example above. The validator method must be declared in the following format
Copy the Code Code as follows: Public function Validatorname ($attribute, $params) {...}
Second, Validator can make the class name of the validator, and when the rule is applied, an instance of the validator class is created and validated in practice. An attached property in the rule that is used for the associated property of the initial instance. The validator class must inherit from the Cvalidator
Tip: When specifying rules for an active record model, we can use special parameters ' on ',
This parameter allows the ' insert ' or ' update ' to be used when inserting or updating the rules respectively. If there is no life, the rule will apply when any call to save ().
Thirdly, Validator can make a pre-defined alias for the validator class. In the example above, "required" is the alias of Crequiredvalidator to verify that the property cannot be empty. The following is a list of predefined validator category names
? Boolean:cbooleanvalidator alias, verify that the value of the property is Cbooleanvalidator::truevalue or Cbooleanvalidator::falsevalue
? Captcha:ccaptchavalidator alias, verify that the value of the property is equal to the value of the verification code shown in CAPTCHA
? Compare:ccomparevalidator, verifies that the value of the property is equal to another property or a constant
? Email:cemailvalidator alias, verify that the value of the property is a legitimate email address
? Default:cdefaultvaluevalidator aliases, assigning a default value to a property
? Exist:cexistvalidator, verify that the value of the property can be found in the column of the table
? File:cfilevalidator alias, verify that the property contains the name of the uploaded file
? Filter:cfiltervalidator aliases, using a filter to convert the form of a property
? In:crangevalidator alias, verify that the property value is in the list of values for the subscription
? The alias of the Length:cstringvalidator ensures that the length of the property value is within the specified range.
? An alias for the match:cregularexpressionvalidator that verifies whether the property matches a regular expression.
? An alias for the numerical:cnumbervalidator that verifies whether the property is a valid number.
? An alias for the required:crequiredvalidator that verifies whether the value of the property is empty.
? An alias for the type:ctypevalidator that verifies whether the property is the specified data type.
? An alias for the unique:cuniquevalidator that verifies whether the property is unique in the Data table field.
? An alias for the url:curlvalidator that verifies whether the property is a valid URL path.
Here are some examples of using pre-defined validators.
Username is Requiredarray (' username ', ' required '),//username must be between 3 and Charactersarray (' username ', ' len Gth ', ' min ' =>3, ' Max ' =>12),//When in register scenario, password must match password2array (' password ', ' compare ', ' Compareattribute ' = ' password2 ', ' on ' = ' register '),//When in login scenario, password must is Authenticatedarray ( ' Password ', ' Authenticate ', ' on ' = ' login ',
3) Setting of security properties
When a model is created, we often need to populate it with attributes based on the user's input. This can be easily achieved by the following batch assignment method
$model =new loginform;if (isset ($_post[' loginform ')) $model->attributes=$_post[' LoginForm '];
The last statement is a batch assignment that assigns each attribute in $_post[' LoginForm ' 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 a property is a security attribute is a critical task. For example, if I expose the primary key of a data table as a security attribute, I can manage the data without permission management by modifying the value of the primary key to attack.
4) Security attributes in version 1.1
In version 1.1, a property is considered safe if the validator is specified in the applicable rule. For example
Array (' Username, password ', ' required ', ' on ' = ' login, register '), array (' email ', ' required ', ' on ' = ' register '),
The user name and password attributes in the above code are not allowed to be empty in the login scenario. The user name and password mailbox are not allowed to be empty in the register scenario. Therefore, if you make a batch assignment in the login scenario, only the user name and password will be assigned, because only the two attributes appear in the validation rule in the login scenario, but if it is in the register scenario, then the three properties will be 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 strategy to determine if a property is a security attribute? Because of a property that already has one or more rules for checking, do I have to worry about it?
It is to be remembered that the validator is used to detect the data entered by the user, rather than the data that we generate with the code (such as timestamps, self-increasing primary keys, etc.). Therefore, do not add validators to attributes that do not require user input.
Sometimes we want to declare that some properties are security properties, but we don't have to specify a validation rule. For example, the body of the article property, we can allow the user any input. In order to achieve this goal, we can use safe rules.
Copy the code as follows: Array (' content ', ' safe ')
There is also an unsafe rule to specify which properties are unsafe
Copy the Code code as follows: Array (' permission ', ' unsafe ')
Unsafe is not commonly used, and it is an exception to the security attributes you have previously defined.
5) Get Validation errors
When validation is complete, any possible errors are stored in the instance of the model. We can retrieve it by calling Cmodel::geterrors () and Cmodel::geterror (). The difference between the two methods is that the first one can return all errors for the specified model property, and the second method returns only the first error.
6) Property Label
When designing a form, we need to display a label for the user's input box to prompt the user for input. Even though we can write in the form again, it's more convenient and flexible if we specify it in the corresponding model.
By default, CModel will simply return the name of the property as a label. This can be customized by overriding the Attributelabels () method. In the next section we will see that assigning tags in a model allows us to create a form form faster and more powerful
It is hoped that this article is helpful to the PHP program design based on YII framework.
Articles you may be interested in:
- Analysis of YII Framework login process
- The method of Cgridview implementation in Yii for batch deletion
- Yii examples of model query techniques based on arrays and objects
- Methods of Yii Authority control (three methods)
- Yii method for uploading files and pictures using Activefilefield control
- Yii implementation method of uploading files using Cuploadedfile
- The query method of Yii database
- A new method to implement pre-and post-logon in Yii
http://www.bkjia.com/PHPjc/1085889.html www.bkjia.com true http://www.bkjia.com/PHPjc/1085889.html techarticle Modeling (model) creation and use in Yii, Yiimodel the method of creating and using model in Yii is analyzed in this paper. Share to everyone for reference, specifically as follows: YII realized ...