Home > Backend Development > PHP Tutorial > How to create and use Model in Yii, yiimodel_PHP tutorial

How to create and use Model in Yii, yiimodel_PHP tutorial

WBOY
Release: 2016-07-12 09:02:15
Original
1115 people have browsed it

How to create and use Model in Yii, yiimodel

This article analyzes the creation and use of Model in Yii with examples. Share it with everyone for your reference, the details are as follows:

YII implements two models, the form model (CFormModel class) and the Active Record model (CAtiveRecord class), both of which inherit from the CModel class. The data model represented by CFormModel is the input collected from the HTML form, encapsulating all logic (such as form validation and other business logic, applied to the form fields). It can store data in memory or, with the help of an Active Record, in a database.

Database connection operation

In config/main.php

'db'=>array(
  'connectionString' => 'mysql:host=localhost;dbname=oss',
  'emulatePrepare' => true,
  'username' => 'root',
  'password' => 'hahaha',
  'charset' => 'utf8',
  //表前缀
  'tablePrefix'=>"oss_"
),

Copy after login

Open comments, php must support pdo

View operation log

//显示日志信息,包括sql的查询信息
array(
  'class'=>'CWebLogRoute',
),

Copy after login

Turn on comments

1. Model based on CActiveRecord

Active Record (AR) is a design pattern that uses an object-oriented approach to abstractly access data. In Yii, each instance of an AR object can be the CActiveRecord class or its subclass. It wraps a row of records in a database table or view and encapsulates all the logic and details of the database that has most of the business logic that must be used using this model. The value of each column field in a row in the database table corresponds to an attribute of the AR object. It maps tables to classes, rows to objects, and columns to the object's data. That is to say, each instance of the Active Record class represents a row of the table in the database. But an Active Record class is not just a mapping relationship between fields in the database table and attributes in the class. It also needs to process some business logic on this data and defines all read and write operations on 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');
}
}

Copy after login

2) Use the methods of the parent class to complete database operations

(1) Insert:

$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();

Copy after login

(2) Select: Several commonly used methods

// find the first row satisfying 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 first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);
$criteria=new CDbCriteria;
$criteria->select='title'; // only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria);
$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID=:postID',
'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);

Copy after login

(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);

Copy after login

(4) Delete

$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$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);

Copy after login

(5) Use transactions

$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
// find and save are two steps which may be intervened by another request
// we therefore use a transaction to ensure consistency and integrity
$post=$model->findByPk(10);
$post->title='new post title';
$post->save();
$transaction->commit();
}
catch(Exception $e)
{
$transaction->rollBack();
}

Copy after login

2. Model based on CFormModel

Before writing the HTML required for the form, we need to decide what data we want the user to enter, and what rules it should comply with. A model class can be used to record this information. The model is the core of maintaining user input and validating it

Depending on how we use the user’s input, we can create two types of models. If the user-entered data is collected, used, and then discarded, we will create a form model; if the user-entered data is saved to the database, we will use an active record. Both models inherit the common interface of the form defined in their base class CModel.

1) Definition of model class

In the following example, we create a LoginForm model to collect user input on the login page. Since the login information is only used for user verification and does not need to be saved, we use the form model to create

class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
}

Copy after login

LoginForm declares three attributes in total, $username, $password, $rememberMe

Used to record the user name, password entered by the user, and the option to remember the login. Because $rememberMe has a default value of false, the corresponding check box is not checked when the form is displayed.

Tip: We use the name "attributes" instead of "properties" to distinguish them from normal properties.

2) Declare validation rules

Once the user-submitted data is populated into the model, we need to check whether they are legal before using it. This is achieved by validating the input with a set of rules. We define validation rules by configuring an array in the rulesers() method

class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
private $_identity;
public function rules()
{
return array(
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.');
}
}
}

Copy after login

The above code specifies that the username and password are required, the password needs to be verified, and rememberMe must be Boolean

Each rule returned in rules() must be in the following format

array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...additional options)

AttributeList is a comma-separated list of attribute names that need to be verified. Validator indicates what validation needs to be done. The optional on parameter indicates the list of scenarios where the rule is applied, (additional options) is the corresponding name-value, which is used to initially correspond to the relevant attributes of the validator

There are three ways to specify a Validator in a rule. First, the Validator can use a method of the class, such as authenticate in the above example. The Validator method must be declared in the following format
Copy code The code is as follows: public function ValidatorName($attribute,$params) { ... }
Secondly, Validator can be the class name of the validator. When the rule is applicable, an instance of the validator class will be created and perform the actual validation. Additional attributes in the rule, used for related attributes of the initial instance. The validator class must inherit from CValidator

Tip: When specifying rules for the active record model, we can use the special parameter ‘on’,

This parameter can be 'insert' or 'update', which allows the rule to be applied when inserting or updating respectively. If there is no life, this rule will apply whenever save() is called.

第三、Validator 可以使验证器类预先定义的别名。在上面的例子中,“required”便是CRequiredValidator的别名,用来验证属性不能为空。下面是预定义的验证器类别名的列表

? boolean:CBooleanValidator的别名,验证属性的值是否是CBooleanValidator::trueValue 或者 CBooleanValidator::falseValue
? captcha:CCaptchaValidator的别名,验证属性的值是否和CAPTCHA中显示的验证码的值相等
? compare:CCompareValidator的别名,验证属性的值是否等于另一个属性或者一个常量
? email:CEmailValidator的别名,验证属性的值是否是个合法的email地址
? default:CDefaultValueValidator的别名,为属性指派一个默认值
? exist:CExistValidator的别名,验证属性的值是否能在表的列里面找到
? file: CFileValidator 的别名, 验证属性是否包含上传文件的名字
? filter:CFilterValidator的别名,使用一个过滤器转换属性的形式
? in: CRangeValidator 的别名, 验证属性值是否在一个预订的值列表里面
? length: CStringValidator 的别名, 确保了属性值的长度在指定的范围内.
? match: CRegularExpressionValidator 的别名, 验证属性是否匹配一个正则表达式.
? numerical: CNumberValidator 的别名, 验证属性是否是一个有效的数字.
? required: CRequiredValidator 的别名, 验证属性的值是否为空.
? type: CTypeValidator 的别名, 验证属性是否是指定的数据类型.
? unique: CUniqueValidator 的别名, 验证属性在数据表字段中是否是唯一的.
? url: CUrlValidator 的别名, 验证属性是否是一个有效的URL路径.

下面我们给出一些使用预定义验证器的例子。

// username is required
array('username', 'required'),
// username must be between 3 and 12 characters
array('username', 'length', 'min'=>3, 'max'=>12),
// when in register scenario, password must match password2
array('password', 'compare', 'compareAttribute'=>'password2',
'on'=>'register'),
// when in login scenario, password must be authenticated
array('password', 'authenticate', 'on'=>'login'),

Copy after login

3) 安全属性的设置

当一个模型创建之后,我们往往需要根据用户的输入,为它填充属性。这可以方便的通过下面批量赋值的方式来实现

$model=new LoginForm;
if(isset($_POST['LoginForm']))
$model->attributes=$_POST['LoginForm'];

Copy after login

最后那条语句便是批量赋值,把$_POST['LoginForm']中每个属性都赋值到对应的模型属性中,它等价于下面的语句

foreach($_POST['LoginForm'] as $name=>$value)
{
if($name is a safe attribute)
$model->$name=$value;
}

Copy after login

声明属性是否是安全属性是个至关重要的工作。例如,如果我把把数据表的主键暴露为安全属性,那么便可以通过修改主键的值,来管理本没有权限管理的数据,进行攻击。

4) 1.1版中的安全属性

在1.1版中,如果属性在适用的规则中指定了验证器,则认为是安全的。例如

array('username, password', 'required', 'on'=>'login, register'),
array('email', 'required', 'on'=>'register'),

Copy after login

上面的代码中用户名和密码属性在login的场景下不允许为空。用户名、密码邮箱在register的场景下不允许为空。因此如果在login的场景下 进 行批量赋值,仅仅用户名和密码会被赋值,因为login场景下验证规则里仅出现了这两个属性,但是如果是在register场景下,那么这三个属性都 会被 赋值。

// 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'];

Copy after login

那么为什么我们使用如此的策略来决定一个属性是否是安全属性呢?因为一个属性,已经有了一个或者多个对个进行校验的规则,那么我还需要担心吗?

需要记住的是,验证器是用来检测用户输入的数据,而不是我们用代码产生的数据(例如 时间戳,自增的主键等)。因此不要给那些不需要用户输入的属性添加验证器。

有时候我们想声明一些属性为安全属性,但是又不必给指定一个验证规则。例如文章的正文属性,我们可以允许用户的任何输入。为了实现这个目标,我们可以用safe规则。
复制代码 代码如下:array('content', 'safe')

对应的也有一个unsafe规则,来指定哪些属性是不安全的
复制代码 代码如下:array('permission', 'unsafe')
unsafe并不常用,对你以前定义的安全属性来说,这是个例外
5) 获取验证错误
当验证结束后,任何可能的错误都存储在模型的实例中。我们可以通过调用CModel::getErrors() 和 CModel::getError()重新获取到。这两个方法的区别在于,第一个可以返回指定模型属性的所有错误,而第二个方法只返回了第一条错误。

6) 属性标签

设计表单的时候,我们需要为用户的输入框显示一个标签,来提示用户输入。尽管我们可以再form中写死,但是如果我们在相应的模型中指定的话会更加方便和灵活

默认情况下,CModel 会简单的返回属性的名字作为标签。这可以通过重写attributeLabels() 方法来自定义。在接下来章节中我们将看到,在模型中指定标签可以让我们更快更强大的创建一个form表单

I hope this article will be helpful to everyone’s PHP programming based on the Yii framework.

Articles you may be interested in:

  • Yii framework login process analysis
  • How to implement batch deletion of CGridView in Yii
  • Yii based on arrays and objects Detailed explanation of model query skills examples
  • yii permission control methods (three methods)
  • yii uses activeFileField control to implement uploading files and pictures
  • yii implements using CUploadedFile to upload files Method
  • Query method of yii database
  • A new method to implement front and backend login processing in Yii

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1085889.htmlTechArticleHow to create and use Model in Yii, yiimodel This article analyzes the Model in Yii with examples How to create and use it. Share it with everyone for your reference, the details are as follows: YII has achieved...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template