A _php example of the creation and application of model in Yii

Source: Internet
Author: User
Tags html form valid email address yii

In this paper, we analyze the creation and use method of model in Yii. Share to everyone for your reference, specific as follows:

YII implements two models, a form model (Cformmodel Class), and an active record model (Cativerecord Class) that inherit from the Cmodel class. The data model represented by Cformmodel is input collected from an HTML form, encapsulating all logic (such as form validation and other business logic, applied to the form's fields). It can store data in memory or, with the help of an active record, into a 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 Action Log

Display log information, including SQL query information
Array (
  ' class ' => ' Cweblogroute ',
),

Open a Comment

A. Model based on Cactiverecord

Active Record (AR) is a design pattern that abstracts access to data in an object-oriented manner, in which each instance of an AR object can be a Cactiverecord class or its subclass. It wraps a row of records in a database table or view, encapsulates all the logic and the details of the hearsay database, and has most of the business logic that must be used. The value of each column field in a database table corresponds to an attribute of the AR object. It maps tables to classes, rows map to objects, and columns map to object data. That is, each instance of an active record class represents a row of tables in the database. However, an Active record class is not merely a mapping of a field in a database table to a property in a class. It also needs to handle some business logic on these data, defining 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 Using 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 commonly used methods

Find the the specified condition $post =post::model ()->find ($condition, $params);
Find the row with 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 "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 ' =>10);
$post =post::model ()->find ($criteria); $post =post::model ()->find (Array (' SELECT ' => ' title ', ' Condition ' => ' postid=:p ostid ', ' params ' =>array ') (':
PostID ' =>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 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 condition
post::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 conditions Post::model
()->updatecounters ($counters , $condition, $params);

(4) Delete

$post =post::model ()->FINDBYPK (10); Assuming there is a post whose ID is
$post->delete ();
Delete the rows matching the specified condition
post::model ()->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 two steps which may is intervened by another request
//We therefore use a Transact Ion to ensure consistency and integrity
$post = $model->findbypk (a);
$post->title= ' new post title ';
$post->save ();
$transaction->commit ();
}
catch (Exception $e)
{
$transaction->rollback ();
}

Two. Model based on Cformmodel

Before writing the HTML needed for a form, we need to decide what data we want users to enter and what rules should be met. A model class can be used to record this information, and the model is the core of keeping user input and validating

Depending on how we use user input, we can create two types of models. If the data entered by the user is collected, used, and 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 forms defined in their same base class Cmodel.

1 Definition of Model class

In the following example, we created a loginform model to collect user input on the landing page. Since the login information is only for user authentication, it does not need to be saved, so we use form model to create

Class LoginForm extends Cformmodel
{public
$username;
public $password;
Public $rememberMe =false;
}

LoginForm declared three attributes (attributes), $username, $password, $rememberMe

The user name, password, and the option to remember to log in. Because $rememberme has the default value false, the corresponding marquee is not checked when the form is displayed.

Hint: 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 if they are legal before using it. This is done by a set of rule validation on the input. We define validation rules in the rulers () method by configuring an array

Class LoginForm extends Cformmodel
{public
$username;
public $password;
Public $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 only 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 code above indicates that the username and password are required, the password needs to be validated, 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 verification needs to be done. The optional on parameter indicates the list of scenarios that the rule applies to, (additional options) is the corresponding Name-value, and is used for the associated 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 Code code as follows:
Public Function Validatorname ($attribute, $params) {...}

Second, the class name of the validator can be Validator, and when the rule is applied, an instance of the validator class is created and validated in practice. The attached property in the rule, for the associated property of the initial instance. Validator class must inherit from Cvalidator

Tip: When assigning rules to the active record model, we can use the special parameter ' on ',

This parameter enables ' insert ' or ' Update ' to allow rules to be applied at the time of insertion or update. If there is no life, the rule will apply in any call to save ().

Third, Validator can make the validator class predefined aliases. In the above example, "required" is an alias for Crequiredvalidator, which verifies that the attribute cannot be empty. The following is a list of predefined validator category names

? Boolean:cbooleanvalidator alias that verifies whether the value of the property is Cbooleanvalidator::truevalue or Cbooleanvalidator::falsevalue
? Captcha:ccaptchavalidator alias that verifies that the value of the property is equal to the value of the validation code shown in Captcha
? Compare:ccomparevalidator alias that verifies whether the value of the property equals another property or a constant
? Email:cemailvalidator alias to verify that the value of the attribute is a valid email address
? Default:cdefaultvaluevalidator alias, assigning a default value to the property
? Exist:cexistvalidator alias to verify that the value of the attribute can be found in the column of the table
? File:cfilevalidator alias to verify that the attribute contains the name of the uploaded file
? Filter:cfiltervalidator alias, using a filter to transform the form of a property
? In:crangevalidator alias to verify that the property value is in the list of values for a subscription
? Length:cstringvalidator alias to ensure that the length of the property value is within the specified range.
? Match:cregularexpressionvalidator alias to verify that the property matches a regular expression.
? Numerical:cnumbervalidator alias to verify that the attribute is a valid number.
? Required:crequiredvalidator alias to verify that the value of the property is null.
? Type:ctypevalidator alias to verify that the property is the specified data type.
? Unique:cuniquevalidator alias that verifies whether the property is unique in a data table field.
? Url:curlvalidator alias to verify that the property is a valid URL path.

Here are some examples of using predefined validators.

Username is required
Array (' username ', ' required '),
//username must to between 3 and characters
Array (' Username ', ' length ', ' min ' =>3, ' Max ' =>12),
/When in register scenario, password must match password2
Arra Y (' password ', ' compare ', ' compareattribute ' => ' password2 ',
' on ' => ' register '),
//while in login scenario , password must is authenticated
array (' Password ', ' Authenticate ', ' on ' => ' login '),

3 The security attribute setting

When a model is created, it is often necessary 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 final statement is a batch assignment that assigns each attribute in the $_post[' LoginForm ' to the corresponding model property, 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 vital task. For example, if I expose the primary key of a datasheet to a security attribute, then I can use the value of the primary key to manage the data that I do not have permission to manage and attack.

4) Security properties 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 (' emails ', ' required ', ' on ' => ') Register '),

The user name and password properties in the above code are not allowed to be NULL in the login scenario. The username and password mailbox are not allowed to be empty under the register scenario. Therefore, if a batch assignment is made in the login scenario, only the username and password will be assigned, because only these two properties appear in the login scenario, but if it is in the register scenario, then these three properties will be assigned.

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 whether 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 timestamp, self-increasing primary key, etc.). Therefore, do not add validators to properties that do not require user input.

Sometimes we want to declare that some properties are security properties, but you do not have to specify a validation rule. For example, the body properties of the article, we can allow the user any input. In order to achieve this goal, we can use the safe rule.

Copy Code code as follows:
Array (' content ', ' safe ')

There is also a unsafe rule that specifies which properties are unsafe

Copy Code code as follows:
Array (' permission ', ' unsafe ')

Unsafe is not commonly used, which is an exception to your previously defined security attributes.
5 Get validation error
When the validation is complete, any possible errors are stored in the instance of the model. We can get it back 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. Although we can write death in form, it will be more convenient and flexible if we specify it in the corresponding model.

By default, Cmodel simply returns the name of the property as a label. This can be customized by overriding the Attributelabels () method. In the next chapters we'll see that specifying tags in the model allows us to create a form forms faster and more powerful

I hope this article will help you with the PHP program design based on the YII framework.

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.