In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the use of the Model model in the Yii framework of PHP". In the daily operation, I believe that many people have doubts about the use of the Model model in the Yii framework of PHP. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about the use of the Model model in the Yii framework of PHP. Next, please follow the editor to study!
Models are part of the MVC schema and are objects that represent business data, rules, and logic.
The model is an instance of CModel or its subclasses. The model is used to maintain the data and the business logic associated with it.
A 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 attribute has a label and can be validated by a series of rules.
Yii implements two types of models: the form model and Active Record. Both 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 the user's input. This data is often captured, used, and then discarded. For example, in a login page, we can use a form model to represent the user name and password information provided by the end user.
Active Record (AR) is a design pattern for abstracting database access through an object-oriented style. Each AR object is an instance of CActiveRecord or its subclasses. Represents a row in the data table. The fields in the row correspond to the properties in the AR object.
A model class can be defined by inheriting yii\ base\ Model or its subclasses, and the base class yii\ base\ Model supports many practical features:
Attribute: represents business data that can be accessed like a normal class attribute or array
Attribute tags: specifies the tag displayed by the attribute
Block assignment: supports assigning many attributes in one step
Validation rules: ensure that the input data conforms to the stated validation rules
Data export: an array that allows model data to be exported to a custom format.
Attribute
The model represents business data through attributes, each of which is like a publicly 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 if it were an object property:
$model = new\ app\ models\ ContactForm;// "name" is the property of the ContactForm model $model- > name = 'example';echo $model- > name
Properties can also be accessed as if they were array unit items, thanks to yii\ base\ Model support for ArrayAccess array access and ArrayIterator array iterators:
$model = new\ app\ models\ ContactForm;// accesses the attribute $model ['name'] =' example';echo $model ['name']; / / iterator traverses the model foreach ($model as $name = > $value) {echo "$name: $value\ n";}
Define attribute
By default, your model class inherits directly from yii\ base\ Model, and all non-static public non-static public member variables are properties. For example, the following ContactForm model class has four properties: name, email, subject and body, and ContactForm model 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 you may need to override magic methods such as _ _ get () and _ _ set () so that the property is accessed like a normal object property.
Attribute tag
When attributes display or get input, you often want to display attribute-related tags, such as assuming a property name is firstName, and in some places, such as form input or error messages, you may want to display First Name tags that are more user-friendly to the end user.
You can call yii\ base\ Model::getAttributeLabel () to get the tag of the attribute, for example:
$model = new\ app\ models\ ContactForm;// is displayed as "Name" echo $model- > getAttributeLabel ('name')
By default, attribute tags are automatically generated from attribute names through the yii\ base\ Model::generateAttributeLabel () method. It automatically converts hump case variable names to multiple uppercase words, such as username to Username and firstName to First Name.
If you don't want to use the automatically generated tag, you can override the yii\ base\ Model::attributeLabels () method to specify the attribute tag explicitly, 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 the application supports multiple languages, the translatable attribute tag can be defined 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, by using the scenario scene of the model, you can return different tags for the same attributes.
Add: attribute tags are part of the view, but declaring tags in the model is usually very convenient, and can be very concise and reusable code.
Scene
The model may be used in multiple scenarios, for example, the User module may collect user login input, or it may be used when the user registers. In different scenarios, the model may use different business rules and logic, for example, the email attribute is mandatory at registration, but not required at login.
The model uses the yii\ base\ Model::scenario attribute to keep track of the usage scene. By default, the model supports a scene named default. The following two ways to set the scene are shown:
/ / scene as an attribute to set $model = new User;$model- > scenario = 'login';// scene sets $model = new User ([' scenario' = > 'login']) by constructing an initialization configuration
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 shown below:
Namespace app\ models;use yii\ db\ ActiveRecord;class User extends ActiveRecord {public function scenarios () {return ['login' = > [' username', 'password'],' register' = > ['username',' email', 'password'],];}}
Add: in both the above and the following examples, the model class inherits yii\ db\ ActiveRecord, because the use of multiple scenarios usually occurs in the ActiveRecord class.
The scenarios () method returns an array whose key is the scene name and the value is the corresponding active attributes activity property. Active attributes can be assigned by blocks and follow validation rules in the above example, username and password are enabled in the login scenario, and email is enabled in addition to username and password in the register scenario.
The default implementation of the scenarios () method returns all scenarios in the verification rules declared by the yii\ base\ Model::rules () method. When scenarios () is overridden, if you want to use the new scenario outside the default scenario, you can write code like this:
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 mainly used in validation and attribute block assignments. You can also use it for other purposes, such as defining different attribute tags based on different scenarios.
Verification rules
When the model receives data entered by the end user, the data should meet certain rules (called validation rules, also known as business rules). For example, if you assume the ContactForm model, you may want to make sure that all properties are not empty and that the email property contains a valid email address. If the value of an attribute does not meet the corresponding business rules, the corresponding error message should be displayed to help the user correct the error.
You can call yii\ base\ Model::validate () to validate the received data, which uses the validation rules declared by yii\ base\ Model::rules () to validate each relevant property, and returns true if no error is found, otherwise it saves the error in the yii\ base\ Model::errors property and returns false, for example:
$model = new\ app\ models\ ContactForm;// user input data is assigned to model properties $model- > attributes =\ Yii::$app- > request- > post ('ContactForm'); if ($model- > validate ()) {/ / all input data is valid all inputs are valid} else {/ / validation failed: $errors is an array containing error messages $errors = $model- > errors;}
Declare model-related validation rules by overriding the yii\ base\ Model::rules () method to specify the rules that the model properties should meet. The following example shows the validation rules declared by the ContactForm model:
Public function rules () {return [/ / name, email, subject and body attributes must have values [['name',' email', 'subject',' body'], 'required'], / / email attribute must be a valid email address [' email', 'email'],];}
A rule can be used to validate one or more attributes, and an attribute can 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 be applied only in a certain scenario, so you can specify the on attribute of the rule, as shown below:
Public function rules () {return [/ / username, email and password must have values in "register" scenarios [['username',' email', 'password'],' required', 'on' = >' register'], / / in "login" scenarios username and password must have values [['username',' password'], 'required',' on' = > 'login'],];}
If the on attribute is not specified, the rules are applied in all scenarios, and the rules applied under the current yii\ base\ Model::scenario are called active rule activity rules.
An attribute only belongs to the activity attribute defined in scenarios () and is validated if the rules () declaration corresponds to one or more activity rules.
Block assignment
Block assignment populates all user input into a model with only one line of code, which populates the input data correspondence directly into the yii\ base\ Model::attributes attribute. The following two pieces of code have the same effect, assigning the form data entered by the end user to the attributes of the ContactForm model, and it is obvious that the first block assignment code is simpler 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 attribute
Block assignment is only applied to the attributes called security attributes listed in the current yii\ base\ Model::scenario scene yii\ base\ Model::scenarios () method of the model. For example, if the User model declares the following scenario, when the current scene is login, only username and password can be assigned by the block, and other attributes will not be assigned.
Public function scenarios () {return ['login' = > [' username', 'password'],' register' = > ['username',' email', 'password'],];}
Add: block assignments are only applied to security attributes because you want to control which attributes will be modified by end-user input data, for example, if the User model has a permission attribute corresponding to the user's permissions, you may only want this attribute to be modified by the administrator in the background interface.
Since the implementation of the default yii\ base\ Model::scenarios () returns all properties and data of yii\ base\ Model::rules (), if this method is not overridden, it means that all properties that appear in the activity validation rule are safe.
To do this, a special validator alias safe is provided to declare which properties are safe and do not need to be validated. The rule of the following example declares that title and description are both security attributes.
Public function rules () {return ['title',' description'], 'safe'],];}
Non-secure attribute
As mentioned above, the yii\ base\ Model::scenarios () method provides two uses: defining which properties should be validated, and defining which properties are safe. In some cases, you may want to validate an attribute but do not want it to be safe, add an exclamation point to the property name in the scenarios () method. For example, the secret attribute looks like the following.
Public function scenarios () {return ['login' = > [' username', 'password','! secret'],];}
When the model is in a login scenario, all three attributes are validated, but only the username and password attributes are assigned by the block. To assign a value to the secret attribute, it must be explicitly assigned as shown in the following example.
$model- > secret = $secret
Data export
Models are usually exported to different formats, for example, you may want to convert a collection of models to JSON or Excel format, the export process can be divided into two steps, the first step, the model is converted into an array; the second step, the array is converted into the desired format. You only need to focus on the first step, because the second step can be done by a general-purpose data converter such as yii\ web\ JsonResponseFormatter.
The easiest way to convert a model to an array is to use the yii\ base\ Model::attributes property, for example:
$post =\ app\ models\ Post::findOne; $array = $post- > attributes
The yii\ base\ Model::attributes property returns the values of all properties declared by yii\ base\ Model::attributes ().
A more flexible and powerful way to convert a model to an array is to use the yii\ base\ Model::toArray () method, which behaves the same as yii\ base\ Model::attributes by default, but allows you to choose which data items called fields are put into the result array and formatted at the same time. In fact, it is the default way to export models to RESTful web service development, see response format for details.
Field
The field is the cell name of the array generated by the model 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, both of which return a list of field definitions, and the fields defined by the fields () method are the default fields, indicating that the toArray () method returns these fields by default. The extraFields () method defines additional available fields, and the $expand parameter is specified by the toArray () method to return these additional available fields. For example, the following code returns all the fields defined by the fields () 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 overriding fields (). The value returned by the fields () method should be an array, the key of the array is the field name, and the value of the array is the corresponding value that can be defined for the field returned by the property name or anonymous function. In the case of a special envoy, if the field name and attribute 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 changes in the properties of the data table or model do not cause your fields to change (make sure that the API at the back end is compatible). Public function fields () {return [/ / the field name is the same as the property name 'id', / / field name is "email" The corresponding attribute name is "email_address" 'email' = >' email_address', / / the field name is "name", and the value returns' name' = > function () {return $this- > first_name through the PHP code. ''. $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 fields public function fields () {$fields = parent::fields (); / / remove some fields that contain sensitive information unset ($fields ['auth_key'], $fields [' password_hash'], $fields ['password_reset_token']); return $fields;}
Warning: since all attributes of the model will be included in the exported array, it is best to check the data to make sure it does not contain sensitive data. If there is sensitive data, you should override the fields () method and filter it out. In the above column, we choose to filter out auth_key and password_hash and password_reset_token.
At this point, the study on "how to use the Model model in PHP's Yii framework" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.