PHP Yii Framework Model learning tutorial, yiimodel_PHP tutorial-php Tutorial

Source: Internet
Author: User
Tags valid email address
The Model learning tutorial in the Yii Framework of PHP, yiimodel. The Model learning tutorial in the Yii Framework of PHP. the yiimodel is part of the MVC Model and is an object that represents business data, rules, and logic. The Model is a learning tutorial for the Model in the Yii Framework of PHP, which is a CModel or its subclass.

A model is a part of the MVC pattern and an object that represents business data, rules, and logic.

The model is a CModel or its subclass instance. The model is used to maintain data and related business logic.

A model is a separate data object. It can be a row in a data table or a user-input form. Each field of the data object corresponds to an attribute in the model. Each attribute has a label and can be verified by a series of rules.

Yii implements two types of models: Form model and Active Record model. Both of them inherit from the same base class CModel.

The form model is an instance of CFormModel. The form model is used to maintain the data obtained from user input. The data is often obtained, used, and discarded. For example, on a logon page, we can use a form model to indicate the user name and password provided by the end user.

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

The Model class can be defined by inheriting yii \ base \ Model or its subclass. the base class yii \ base \ Model supports many practical features:

  • Attribute: business data that can be accessed like a common class attribute or array;
  • Attribute tag: specify the tag displayed for the attribute;
  • Block assignment: you can assign values to multiple attributes in one step;
  • Verification rules: ensure that the input data complies with the stated verification rules;
  • Data export: Allows you to export model data to an array in custom format.

Attribute

The Model uses attributes to represent business data. each attribute is like the public accessible attribute of the Model. yii \ base \ Model: attributes () specifies the attributes of the Model.

You can access the attributes of a model just like accessing an object property:

$ Model = new \ app \ models \ ContactForm; // "name" is the attribute of the ContactForm model $ model-> name = 'example '; echo $ model-> name;

You can also access attributes like accessing array unit items. thanks to yii \ base \ Model for supporting ArrayAccess array access and ArrayIterator array iterator:

$ Model = new \ app \ models \ ContactForm; // access the attribute $ model ['name'] = 'example 'like an array unit item '; echo $ model ['name']; // iterator traverses the model foreach ($ model as $ name = >$ value) {echo "$ name: $ value \ n ";}

Define attributes

By default, your Model class is directly inherited from yii \ base \ Model. all non-static public member variables are attributes. For example, the following ContactForm model class has four attributes: name, email, subject and body. 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 method is to overwrite yii \ base \ Model: attributes () to define attributes. this method returns the attribute name of the Model. For example, yii \ db \ ActiveRecord returns the column name of the corresponding data table as its attribute name. Note that the magic methods such as _ get () and _ set () may need to be overwritten () make attributes accessible like common object attributes.

Attribute tag

When an attribute is displayed or an input is obtained, tags related to the attribute are often displayed. for example, if an attribute is named firstName, in some places, such as form input or error information, you may want to display the First Name tag that is more friendly to end users.

You can call yii \ base \ Model: getAttributeLabel () to obtain the attribute tag, for example:

$ Model = new \ app \ models \ ContactForm; // display as "Name" echo $ model-> getAttributeLabel ('name ');

By default, attribute labels are automatically generated from attribute names using the yii \ base \ Model: generateAttributeLabel () method. it automatically converts the camper case variable Name to multiple uppercase words, such as username to Username and firstName to First Name.

If you do not want to use the automatically generated tag, you can overwrite the yii \ base \ Model: attributeLabels () method to explicitly specify the attribute tag. 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',    ];  }}

If an application supports multiple languages, you can translate attribute tags. you can define them in the yii \ base \ Model: attributeLabels () method, as shown below:

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 tags based on conditions. for example, you can use the scenario of the model to return different tags for the same attributes.

Note: attribute labels are the visible part, but it is usually very convenient to declare tags in the model, and the itinerary is very simple and reusable code.
Scenario

The model may be used in multiple scenarios. for example, the User module may collect User login input or use it during User registration. In different scenarios, the model may use different business rules and logic. for example, email attributes are mandatory during registration, but are not required during login.

The Model uses the yii \ base \ Model: scenario attribute to keep track of the application scenario. by default, the Model supports a scenario named default. The following describes how to set the scenario:

// Set $ model = new User as an attribute in the scenario; $ model-> scenario = 'login '; // Set $ model = new User by constructing initialization configuration (['scenario' => 'login']);

By default, the scenarios supported by the Model are determined by the verification rules stated in the Model, but you can customize the behavior by overwriting 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'],    ];  }}

Supplement: in the preceding and following examples, the model class inherits yii \ db \ ActiveRecord, because the use of multiple scenarios usually occurs in the Active Record class.
The scenarios () method returns an array. the key of the array is the scene name and the value is the corresponding active attributes activity attribute. Activity attributes can be assigned by blocks and follow verification rules. in the preceding example, username and password are enabled in the login scenario. in the register scenario, emails except username and password are also enabled.

By default, the scenarios () method returns the scenario in all authentication rules stated by the yii \ base \ Model: rules () method. When scenarios () is overwritten, if you want to use a new scenario outside 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;  }}

The scenario features are mainly used in verification and attribute block assignment. You can also use it for other purposes. for example, you can define different attribute tags based on different scenarios.

Verification rules

When the model receives the data input by the end user, the data must meet certain rules (verification rules, also known as business rules ). For example, assuming the ContactForm model, you may want to ensure that all attributes are not empty and the email attribute contains a valid email address. if the value of an attribute does not meet the corresponding business rules, the corresponding error information should be displayed to help the user correct the error.

You can call yii \ base \ Model: validate () to verify the received data. This method uses yii \ base \ Model: rules () if no error is found, true is returned. Otherwise, the error is saved in the yii \ base \ Model: errors attribute and false is returned, for example:

$ Model = new \ app \ models \ ContactForm; // assign a value to the model attribute $ model-> attributes = \ Yii :: $ app-> request-> post ('contactform'); if ($ model-> validate ()) {// all input data is valid all inputs are valid} else {// verification failed: $ errors is an array containing error information $ errors = $ model-> errors ;}

Specify the rules that the Model attributes should meet by overwriting the yii \ base \ Model: rules () method to declare the Model-related verification rules. The following example shows the verification rules stated by the ContactForm model:

Public function rules () {return [// name, email, subject, and body attributes must have values [['name', 'Email ', 'subobject', 'body'], 'requestred'], // The email attribute must be a valid email address ['email ', 'Email'],];}

One rule can be used to verify one or more attributes. one attribute can correspond to one or more rules.

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.