A model is a part of the MVC pattern that represents the objects of business data, rules, and logic.
You can inherit Yii\base\model or its subclasses to define the model class.
The properties included in the base class are:
1. Properties: Represents business data that can be accessed like a normal class property or array
2. Properties Tab: Specify the label that the property displays
3. Block assignment: Supports assigning values to many properties in one step
4. Validation rules: Ensure that the input data conforms to the stated validation rules
5. Data export: Allow model data to be exported as an array of custom formats
The model class is also the base class for more advanced models such as active record activity records.
Property
The model represents the business logic through attributes, each of which is like a publicly accessible property of the model.
Attributes () Specifies the properties owned by the model.
Access the properties of the model as you would access an object property:
$model = new \app\models\contactform;//"Name" is the property of the Contactform model $model->name = ' example '; Echo $model->name;
Access properties as you would access array cell items, because Yii\base\model supports arrayaccess array access and Arrayiterator array iterators:
$model = new \app\models\contactform;//accesses the property like an array cell entry $model[' name '] = ' example '; Echo $model [' name '];
Iterator Traversal model
foreach ($model as $name = = $value) {
echo "$name: $value \ n";
Defining properties
All non-static public member variables are properties.
Contactform model class has four properties
Name, email, subject and body, the Contactform model is used to represent the input data obtained from an HTML form.
Namespace App\models;use yii\base\model;class Contactform extends model{public $name; public $email; public $subject; public $body;}
Another way is to override Yii\base\model::attributes () to define the property, which returns the property name of the model, ActiveRecord returns the corresponding data table column name as the property name.
Property labels
When a property displays or gets input, it is often necessary to display a property-related label, a property named FirstName, which can be changed to a friendlier first name tag at the form input or at the error prompt.
You can call [[Yii\base\model::getattributelabel ()]] to get the label of the property, for example:
$model = new \app\models\contactform;//displayed as "name" Echo $model->getattributelabel (' name ')
By default, the property label is automatically generated from the property name, and the Camel case variable name is automatically converted to multiple first-letter uppercase words.
If you do not want to use auto-generated labels, you can override the [[Yii\base\model::attributelabels ()]] method to explicitly specify the property label
Public Function Attributelabels () {return [' name ' = ' Your name ', ' email ' = ' Your email address ', ' Subje CT ' = ' Subject ', ' body ' = ' Content ', ';}
In cases where the application supports multiple languages, the attribute tag can be translated and defined in the [[Yii\base\model::attributelabels () |attributelabels ()]] method, as follows:
Public Function Attributelabels () {return [' name ' = + \yii::t (' app ', ' Your name '), ' email ' + \yii::t (' app ', ' Your email address '), ' subject ' + \yii::t (' app ', ' Subject '), ' body ' + \yii::t (' app ', ' Content '),];}
You can also define labels based on criteria, such as returning different labels to the same property by using the model's scenario scene.
Scene
The model may be used in multiple scenarios, the user module may be collecting login input from users, or it may be used when the user registers. In different scenarios, the model may use different business rules and logic, such as email attributes that are mandatory at the time of registration, but not required at logon.
The model uses the Yii\base\model::scenario property to keep track of the scene, and by default, the model supports a scene named default.
To set the scene:
The scene is set as a property $model = new User; $model->scenario = ' login ';//The scene is set by constructing the initialization configuration $model = new User ([' scenario ' = ' login ']) ;
By default, the scenarios that the model supports are determined by the validation rules declared in the model, but can be customized by overwriting Yii\base\model::scenarios ().
Namespace App\models;use yii\db\activerecord;class User extends activerecord{public function Scenarios () { return [ ' login ' = [' username ', ' password '], ' register ' = ' [' username ', ' email ', ' password '], ]; }}
The scenarios () method returns an array whose key is the scene name and the value of the corresponding active attributes activity property.
Activity properties can be assigned by blocks and follow validation rules in the above example, username and password are enabled in the login scenario, and in the register scenario, the email is enabled in addition to username and password.
The default implementation of the scenarios () method returns the scene in the validation rule declared by all [[Yii\base\model::rules ()]] methods, and when overwriting scenarios (), if you want to use a new scene outside of the default scenario, you can write code similar to the following:
Namespace App\models;use yii\db\activerecord;class User extends activerecord{public function scenarios () {$scenario s = Parent::scenarios (); $scenarios [' login '] = [' username ', ' password ']; $scenarios [' register '] = [' username ', ' email ', ' password ']; return $scenarios; }}
Scene features are primarily used in validation and attribute block assignment. You can also use it for other purposes, for example, to define different attribute tags based on different scenarios.
Validation rules
When the model receives data entered by the end user, the data should satisfy a certain rule (called a validation rule, also known as a business rule).
You can invoke [[Yii\base\model::validate ()]] to validate the received data, which validates each related property using the validation rules of the Yii\base\model::rules () declaration, and returns true if no error is found. Otherwise it will save the error in the [[Yii\base\model::errors]] property and return False
$model = new \app\models\contactform;//user input data assignment to model properties $model->attributes = \yii:: $app->request->post (' Contactform '), if ($model->validate ()) {//All input data valid all inputs is valid} else {//validation failed: $errors is an array containing error information $erro rs = $model->errors;}
Declare the model-related validation rules by overriding the [[Yii\base\model::rules ()]] method to specify the rules that the model properties should satisfy. The following example shows the validation rules for the Contactform model declaration:
Public Function rules () {return [//name, email, subject and body attributes must have values [[' Name ', ' email ', ' subject ', ' body '], ' req Uired '],//email attribute must be a valid e-mail address [' email ', ' email ',];}
A rule can be used to validate one or more properties, and one property may correspond to one or more rules.
Sometimes you want a rule to apply only in a certain scenario, so you can specify the rule's on property as follows:
Public Function rules () {return [////In "register" scenario username, email and password must have value [[' Username ', ' email ', ' passwo Rd '], ' required ', ' on ' = ' register '],//In the "Login" scenario username and password must have values [[' Username ', ' password '], ' requ Ired ', ' on ' = ' login '], ';}
If you do not specify an on property, the rule is applied in all scenarios, and an attribute will only belong to the activity attribute defined in scenarios () and is validated in case the rules () declaration corresponds to one or more of the active rule.
Block Assignment value
Block assignment fills all user input into a model with just one line of code, which is handy for populating the input data directly into the Yii\base\model::attributes property.
$model = new \app\models\contactform; $model->attributes = \yii:: $app->request->post (' contactform ');
$model = new \app\models\contactform; $data = \yii:: $app->request->post (' contactform ', []); $model->name = Isset ($data [' name '])? $data [' name ']: null; $model->email = Isset ($data [' email '])? $data [' email ']: null; $model->subject = Isset ($data [' Subject '])? $data [' subject ']: null; $model->body = Isset ($data [' body '])? $data [' body ']: null;
Security properties
The block assignment is applied only to attributes that are called security attributes listed in the model's current scene, and the user model declares the following scenario where only username and password can be assigned to a block when the current scene is login, and other properties are not assigned to the block.
Public function Scenarios () {return [' login ' = [' username ', ' password '], ' register ' = [' username ', ' email ' , ' password '],];}
Non-security attributes
As mentioned above, the [[Yii\base\model::scenarios ()]] method provides two uses: defines which properties should be validated and which properties are safe. In some cases, you may want to verify a property but do not want to make it safe, you can add an exclamation mark to the property name in the scenarios () Method!. For example, the Secret property is as follows.
Public function Scenarios () {return [' login ' = [' username ', ' password ', '!secret '],];}
When the model is in the login scenario, three properties are validated, but only the username and Password properties are assigned to the block, and to assign a value to the secret property, it must be explicitly assigned as shown in the following example.
$model->secret = $secret;
Data export
The simplest way to convert a model to an array is to use the Yii\base\model::attributes property, for example:
$post = \app\models\post::findone (n); $array = $post->attributes;
The Yii\base\model::attributes property returns the value of all yii\base\model::attributes () declared properties.
A more flexible and powerful way to convert a model to an array is to use the [[Yii\base\model::toarray ()]] method, which behaves by default and [[Yii\base\model::attributes]]. However, it allows you to select which data items are called fields to be placed in the result array and formatted at the same time.
Field
field is the cell name of the array generated by the model by calling [[Yii\base\model::toarray ()]]
By default, the field name corresponds to the property name, but you can override [[Yii\base\model::fields () |fields ()]] and/or [[Yii\base\model::extrafields () |extrafields ()] ] method to change this behavior, two methods return a list of field definitions, the fields defined by the field () method are default fields, and the ToArray () method returns these fields by default. The Extrafields () method defines additional fields that are available, and the ToArray () method specifies the $expand parameter to return these additional available fields.
Fields () can be added, deleted, renamed, and redefined by overwriting field (), the value of the fields () method should be an array, the key is the field name, the value of the array is the corresponding value for the field that can be returned for the property name or anonymous function. In case of special Envoy, if the field Name property definition name is the same, you can omit the array key, for example:
Explicitly list each field, especially if you want to make sure that the data table or model property changes do not cause your field to change (to ensure that the backend API is compatible). public function field () {return [///Fields and property names ' id ',// The field name is "email", the corresponding property is named "email_address" ' email ' = ' email_address ',//field is named "Name", the value is returned by PHP code ' name ' = Func tion () {return $this->first_name. ‘ ‘ . $this->last_name; }, ];} Filter out some fields, especially if you want to inherit the parent class implementation and do not want to use some sensitive field public function fields () {$fields = Parent::fields (); Remove some fields containing sensitive information unset ($fields [' Auth_key '], $fields [' Password_hash '], $fields [' Password_reset_token ']; return $fields;}
Since all the properties of the model are included in the exported array, it is best to check the data to ensure that no sensitive data is included, if there is sensitive data that should be filtered out by the fields () method, in the above sake, we choose to filter out Auth_key, Password_hashand Password_ Reset_token.
• Can contain attributes to showcase business data;
• Can include validation rules to ensure data is valid and complete;
• Can include methods to implement business logic;
• Requests, sessions, and other environmental data should not be accessed directly, and the data should be passed to the model by the Controller;
• Avoid embedding HTML or other presentation code, which is best handled in the view;
• Avoid too many scenarios in a single model.
To ensure good model maintenance, the following strategies are best used:
• Define a collection of model base classes that can be shared by multiple application principals or modules. These model classes should contain a common set of minimum rules and logic.
• In each application body or module that uses the model, the specific model class is defined by inheriting the corresponding model base class, which contains the rules and logic specified by the application principal or module.
YII2 Model Overview