PHP's YII Framework for Model Modeling tutorial, yiimodel_php Tutorial

Source: Internet
Author: User
Tags access properties html form

PHP's YII framework for Model Learning tutorial, Yiimodel


Models are part of the MVC pattern and are objects that represent business data, rules, and logic.

A model is an instance of CModel or its subclasses. Models are used to persist data and the business logic associated with it.

The model is a separate data object. It can be a row in a data table, or a form entered by a user. Each field of the data object corresponds to an attribute in the model. Each property has a label and can be validated through a series of rules.

YII implements two types of models: the form model and the Active Record. Both inherit from the same base class CModel.

The form model is an instance of Cformmodel. The form model is used to keep the data obtained from the user's input. These data are often acquired, used, and then discarded. For example, on a login page, we can use the form model to represent the user name and password information provided by the end user.

Active Record (AR) is a design pattern used to abstract database access through object-oriented styles. Each AR object is an instance of a Cactiverecord or its subclasses. Represents a row in a data table. The fields in the row correspond to the properties in the AR object.

Model classes can be defined by inheriting Yii\base\model or its subclasses, and the base class Yii\base\model supports many useful features:

    • Property: Represents the business data that can be accessed like a normal class property or array;
    • Attribute tag: Specifies the label that the property displays;
    • Block assignment: Supports assigning values to many attributes in one step;
    • Validation rules: Ensure that the input data conforms to the stated validation rules;
    • Data export: Allows model data to be exported as an array of custom formats.

Property

The model represents the business data through attributes, each of which is like a public accessible property of the model, and yii\base\model::attributes () specifies the properties owned by the model.

You can 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;

You can also access properties as you would access array cell items, thanks to Yii\base\model support for arrayaccess array access and Arrayiterator array iterators:

$model = new \app\models\contactform;//accesses the property like an array cell item $model[' name '] = ' example '; Echo $model [' name '];//iterator traversal model foreach ($model as $name = $value) {  echo "$name: $value \ n";}

Defining properties

By default, your model class inherits directly from Yii\base\model, and all non-static public non-static common member variables are attributes. For example, the following Contactform model class has four properties name, email, subject and body, and the Contactform model is used to represent the input data obtained from the 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. For example, Yii\db\activerecord returns the corresponding data table column name as its property name, note that it may be necessary to override the Magic method such as __get (), __set () so that the property is accessed like a normal object property.

Property labels

When a property displays or gets input, it is often necessary to display property-related labels, such as assuming that a property is named FirstName, where you might want to display a first Name tag that is friendlier to the end user in some places, such as form input or error messages.

You can call Yii\base\model::getattributelabel () to get the label of the property, for example:

$model = new \app\models\contactform;//is displayed as "name" Echo $model->getattributelabel (' name ');

By default, property labels are automatically generated from the property name through the Yii\base\model::generateattributelabel () method. It automatically converts the camel-cased variable name to multiple, capitalized words, such as username to username, firstName to first name.

If you do not want to use auto-generated labels, you can override the Yii\base\model::attributelabels () method to explicitly specify property labels, for example:

Namespace App\models;use yii\base\model;class Contactform extends model{public  $name;  public $email;  public $subject;  public $body;  Public Function Attributelabels ()  {    return [      ' name ' = ' Your name ',      ' email ' = ' Your ' email Address ',      ' subject ' = ' 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 () 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 even define labels by criteria, for example, by using the model's scenario scene, you can return different labels for the same property.

Add: Property labels are part of the view, but it is often very convenient to declare labels in the model, and the travel is very concise and reusable code.
Scene

The model may be used in multiple scenarios, such as 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 are not required when logging in.

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, which shows two ways to set up the scene as follows:

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 supported by the model are determined by the validation rules declared in the model, but you can customize the behavior by overriding the Yii\base\model::scenarios () method, as follows:

Namespace App\models;use yii\db\activerecord;class User extends activerecord{public  function Scenarios ()  {    return [      ' login ' = [' username ', ' password '],      ' register ' = ' [' username ', ' email ', ' password '],    ];  }}

Add: In the above and below examples, model classes are inherited Yii\db\activerecord, because the use of multiple scenes typically occurs in the active Record class.
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 all the scenarios in the validation rules declared by the Yii\base\model::rules () method, 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 ()  {    $scenarios = 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). For example, assuming the Contactform model, you might want to ensure that all properties are not empty and that the email attribute contains a valid mailbox address, and that if the value of a property does not meet the corresponding business rule, the corresponding error message should be displayed to help the user fix the error.

You can call 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 errors are found. Otherwise, it will save the error in the Yii\base\model::errors property and return False, for example:

$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  $errors = $model->errors;}

The model-related validation rules are declared 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 '], ' Required ',    //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. For more information on how to declare validation rules, please refer to the Validation input section.

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 ', ' p Assword '], ' required ', ' on ' = ' register '],    //In the "Login" scenario username and password must have values    [[' Username ', ' password '] , ' Required ', ' on ' = ' login '], '  ;}

If the on property is not specified, the rule is applied in all scenarios, and the rule applied under the current Yii\base\model::scenario is called the active rule activity rules.

An attribute only belongs to the activity attribute defined in scenarios () and is validated in the case that the Rules () declaration corresponds to one or more rule of activity.

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. The following two-paragraph code effect is the same, which assigns the form data entered by the end user to the properties of the Contactform model, and it is clear that the previous block has been assigned a code that is concise and less error-prone than the latter.

$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 applies only to properties that are called security properties listed in the model's current Yii\base\model::scenario scene Yii\base\model::scenarios () method, for example, if the user model declares the following scenario, When the current scene is login, only username and password can be assigned to a block, and other properties will not be assigned a value.

Public function Scenarios () {  return [    ' login ' = [' username ', ' password '],    ' register ' = [' username ' , ' email ', ' password ',  ];}

Add: The block assignment is only applied to security attributes, because you want to control which properties are modified by the end user input data, for example, if the user model has a permission attribute that corresponds to users ' permissions, you may want to let this property be modified by the administrator in the background interface only.
Because the implementation of the default Yii\base\model::scenarios () returns all properties and Data yii\base\model::rules (), if this method is not overridden, it means that all properties that appear in the active validation rule are safe.

To do this, provide a special name for the safe validator to state which properties are safe and do not need to be validated, as the following example rules affirm that both title and description are security attributes.

Public Function Rules () {  return [[    ' title ', ' description '], ' safe '], '  ;}

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 to define. 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

Models are typically exported to different formats, for example, you might want to convert a collection of models into JSON or Excel, and the export process can be decomposed into two steps, the first step, the model conversions to an array, and the second step, the arrays are converted to the desired format. You only need to focus on the first step, because the second step can be accomplished by a generic data converter such as Yii\web\jsonresponseformatter.

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.

The 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 the same, 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. In fact, it is the default method of exporting the model to RESTful Web services development, see the response format for details.

Field

The field is the cell name of the array that the model generates by calling Yii\base\model::toarray ().

By default, field names correspond to property names, but you can change this behavior by overriding the Yii\base\model::fields () and/or Yii\base\model::extrafields () methods, and all two methods return a list of field definitions. Fields defined by the field () method are default fields, which indicate that 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. For example, the following code returns all fields defined by the field () method and the Prettyname and Fulladdress fields defined by the Extrafields () method.

$array = $model->toarray ([], [' Prettyname ', ' fulladdress ']);
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 and property definition name are 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 (ensure that the backend API is compatible). public function field () {  return [    //Field name and property name]    Id ',    //Field name "email", corresponding attribute named "email_address"    ' email ' = ' email_address ',    //field named "Name", Value returned    by PHP code ' Name ' = function () {      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;}

Warning: Since all properties of the model will be 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, should be covered by the fields () method to filter out, in the above sake, we choose to filter out Auth_key, Password_hash and password _reset_token.
Best practices

A model is a central place to represent business data, rules, and logic, often reused in many places, and in a well-designed application, the model is usually more than the controller code.

To sum up, the model:

    • Can contain attributes to display business data;
    • Can include validation rules to ensure data is valid and complete;
    • Can include methods to implement business logic;
    • The request, session, and other environment data should not be accessed directly, and the data should be passed to the model by the Controller;
    • You should avoid embedding HTML or other presentation code, which is best handled in the view;
    • Avoid too many scenarios in a single model.

The last piece of advice should always be considered when developing large, complex systems, where the model is large and used in many places, so it will include the need for ruleset and business logic, and finally maintaining these model code is a nightmare, since a simple modification can affect many places, and it is best to use the following strategies to ensure that the model is well maintained:

Defines 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 principal 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.
For example, in the Advanced application template, you can define a model base class Common\models\post, and then in the foreground application, define and use a concrete model class Frontend\models\post that inherits Common\models\post, Backend\models\post can be similarly defined in a background app. With this strategy, you know that frontend\models\post only corresponds to the foreground app, and if you modify it, you don't have to worry about the changes that will affect the background app.

Articles you may be interested in:

    • A detailed description of the use of the front-end resource bundle in PHP's YII framework
    • Introduction to some advanced usage of caching in the YII framework of PHP
    • In-depth parsing of PHP's caching capabilities in the YII framework
    • The use of view view in the Yii framework of PHP is advanced
    • A detailed approach to creating views and rendering views in the PHP yii framework
    • Controller controllers in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework
    • The definition and binding methods of behavior in the YII framework of PHP
    • In-depth explanation of properties in the Yii framework of PHP
    • A detailed description of the installation and use of PHP's YII framework Extension

http://www.bkjia.com/PHPjc/1117073.html www.bkjia.com true http://www.bkjia.com/PHPjc/1117073.html techarticle in PHP's YII framework, the model model is a part of the MVC paradigm, and is an object representing business data, rules, and logic, Yiimodel. A model is a CModel or a subclass of the real ...

  • Related Article

    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.