国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
A learning tutorial for the Model model in PHP's Yii framework. The yiimodel
您可能感興趣的文章:
Home Backend Development PHP Tutorial Learning tutorial for Model model in PHP's Yii framework, yiimodel_PHP tutorial

Learning tutorial for Model model in PHP's Yii framework, yiimodel_PHP tutorial

Jul 12, 2016 am 08:55 AM
php yii

A learning tutorial for the Model model in PHP's Yii framework. The yiimodel

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

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

Models are separate data objects. It can be a row in a data table, or a user-entered form. Each field of the data object corresponds to an attribute in the model. Each attribute has a label and can be verified through a series of rules.

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

Form models are instances of CFormModel. The form model is used to hold data obtained from the user's input. This data is often acquired, used, and then discarded. For example, in a login page, we can use the form model to represent the username and password information provided by the end user.

Active Record (AR) is a design pattern for abstracting database access in an object-oriented style. Each AR object is an instance of CActiveRecord or one of its subclasses. Represents a row in the data table. The fields in the row correspond to properties in the AR object.

Model classes can be defined by inheriting yiibaseModel or its subclasses. The base class yiibaseModel supports many practical features:

  • Attribute: Represents business data that can be accessed like a normal class attribute or array;
  • Attribute label: The label displayed by the specified attribute;
  • Block assignment: supports assigning values ??to many attributes in one step;
  • Validation rules: Ensure that the input data conforms to the declared validation rules;
  • Data export: Allows model data to be exported as an array in a custom format.

Attributes

The model represents business data through attributes. Each attribute is like a publicly accessible attribute of the model. yiibaseModel::attributes() specifies the attributes owned by the model.

A model's properties can be accessed just like an object's properties:

$model = new \app\models\ContactForm;

// "name" 是ContactForm模型的屬性
$model->name = 'example';
echo $model->name;

Properties can also be accessed like array cell items, thanks to yiibaseModel's support for ArrayAccess and ArrayIterator array iterators:

$model = new \app\models\ContactForm;

// 像訪問數(shù)組單元項一樣訪問屬性
$model['name'] = 'example';
echo $model['name'];

// 迭代器遍歷模型
foreach ($model as $name => $value) {
  echo "$name: $value\n";
}

Define attributes

By default, your model class inherits directly from yiibaseModel, and all non-static public non-static public member variables are properties. For example, the following ContactForm model class has four attributes name, email, subject and body. The ContactForm model is used to represent input data obtained from an 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 yiibaseModel::attributes() to define attributes. This method returns the attribute name of the model. For example, yiidbActiveRecord returns the corresponding data table column name as its attribute name. Note that you may need to override magic methods such as __get(), __set() to make the attributes be accessed like ordinary object attributes.

Attribute tag

When an attribute is displayed or input is obtained, it is often necessary to display attribute-related labels. For example, assuming an attribute is named firstName, in some places such as form input or error messages, you may want to display a label that is more friendly to the end user. First Name tag.

You can call yiibaseModel::getAttributeLabel() to get the label of the attribute, for example:

$model = new \app\models\ContactForm;

// 顯示為 "Name"
echo $model->getAttributeLabel('name');

By default, attribute labels are automatically generated from attribute names through the yiibaseModel::generateAttributeLabel() method. It will automatically convert camel case variable names into multiple words with the first letter capitalized, for example, username is converted to Username, firstName Convert to First Name.

If you don’t want to use automatically generated labels, you can override the yiibaseModel::attributeLabels() method to specify attribute labels 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',
    ];
  }
}

When the application supports multiple languages, the attribute labels can be translated and can be defined in the yiibaseModel::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 labels based on conditions, such as by using a model's scenario to return different labels for the same property.

Supplement: Attribute labels are part of the view, but declaring labels in the model is usually very convenient and can lead to 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 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 during registration, but not required during login.

The model uses the yiibaseModel::scenario attribute to keep track of usage scenarios. By default, the model supports a scenario named default. Two methods of setting the scenario are shown below:

// 場景作為屬性來設置
$model = new User;
$model->scenario = 'login';

// 場景通過構造初始化配置來設置
$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 yiibaseModel::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'],
    ];
  }
}

補充:在上述和下述的例子中,模型類都是繼承yii\db\ActiveRecord, 因為多場景的使用通常發(fā)生在Active Record 類中.
scenarios() 方法返回一個數(shù)組,數(shù)組的鍵為場景名,值為對應的 active attributes活動屬性。 活動屬性可被 塊賦值 并遵循驗證規(guī)則在上述例子中,username 和 password 在login場景中啟用,在 register 場景中, 除了 username and password 外 email也被啟用。

scenarios() 方法默認實現(xiàn)會返回所有yii\base\Model::rules()方法申明的驗證規(guī)則中的場景, 當覆蓋scenarios()時,如果你想在默認場景外使用新場景,可以編寫類似如下代碼:

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;
  }
}

場景特性主要在驗證 和 屬性塊賦值 中使用。 你也可以用于其他目的,例如可基于不同的場景定義不同的 屬性標簽。

驗證規(guī)則

當模型接收到終端用戶輸入的數(shù)據(jù),數(shù)據(jù)應當滿足某種規(guī)則(稱為 驗證規(guī)則, 也稱為 業(yè)務規(guī)則)。 例如假定ContactForm模型,你可能想確保所有屬性不為空且 email 屬性包含一個有效的郵箱地址, 如果某個屬性的值不滿足對應的業(yè)務規(guī)則,相應的錯誤信息應顯示,以幫助用戶修正錯誤。

可調用 yii\base\Model::validate() 來驗證接收到的數(shù)據(jù), 該方法使用yii\base\Model::rules()申明的驗證規(guī)則來驗證每個相關屬性, 如果沒有找到錯誤,會返回 true,否則它會將錯誤保存在 yii\base\Model::errors 屬性中并返回false,例如:

$model = new \app\models\ContactForm;

// 用戶輸入數(shù)據(jù)賦值到模型屬性
$model->attributes = \Yii::$app->request->post('ContactForm');

if ($model->validate()) {
  // 所有輸入數(shù)據(jù)都有效 all inputs are valid
} else {
  // 驗證失?。?errors 是一個包含錯誤信息的數(shù)組
  $errors = $model->errors;
}

通過覆蓋 yii\base\Model::rules() 方法指定模型屬性應該滿足的規(guī)則來申明模型相關驗證規(guī)則。 下述例子顯示ContactForm模型申明的驗證規(guī)則:

public function rules()
{
  return [
    // name, email, subject 和 body 屬性必須有值
    [['name', 'email', 'subject', 'body'], 'required'],

    // email 屬性必須是一個有效的電子郵箱地址
    ['email', 'email'],
  ];
}

一條規(guī)則可用來驗證一個或多個屬性,一個屬性可對應一條或多條規(guī)則。 更多關于如何申明驗證規(guī)則的詳情請參考 驗證輸入 一節(jié).

有時你想一條規(guī)則只在某個 場景 下應用,為此你可以指定規(guī)則的 on 屬性,如下所示:

public function rules()
{
  return [
    // 在"register" 場景下 username, email 和 password 必須有值
    [['username', 'email', 'password'], 'required', 'on' => 'register'],

    // 在 "login" 場景下 username 和 password 必須有值
    [['username', 'password'], 'required', 'on' => 'login'],
  ];
}

如果沒有指定 on 屬性,規(guī)則會在所有場景下應用, 在當前yii\base\Model::scenario 下應用的規(guī)則稱之為 active rule活動規(guī)則。

一個屬性只會屬于scenarios()中定義的活動屬性且在rules()申明對應一條或多條活動規(guī)則的情況下被驗證。

塊賦值

塊賦值只用一行代碼將用戶所有輸入填充到一個模型,非常方便, 它直接將輸入數(shù)據(jù)對應填充到 yii\base\Model::attributes 屬性。 以下兩段代碼效果是相同的,都是將終端用戶輸入的表單數(shù)據(jù)賦值到 ContactForm 模型的屬性, 明顯地前一段塊賦值的代碼比后一段代碼簡潔且不易出錯。

$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;

安全屬性

塊賦值只應用在模型當前yii\base\Model::scenario場景yii\base\Model::scenarios()方法 列出的稱之為 安全屬性 的屬性上,例如,如果User模型申明以下場景, 當當前場景為login時候,只有username and password 可被塊賦值,其他屬性不會被賦值。

public function scenarios()
{
  return [
    'login' => ['username', 'password'],
    'register' => ['username', 'email', 'password'],
  ];
}

補充: 塊賦值只應用在安全屬性上,因為你想控制哪些屬性會被終端用戶輸入數(shù)據(jù)所修改, 例如,如果 User 模型有一個permission屬性對應用戶的權限, 你可能只想讓這個屬性在后臺界面被管理員修改。
由于默認yii\base\Model::scenarios()的實現(xiàn)會返回yii\base\Model::rules()所有屬性和數(shù)據(jù), 如果不覆蓋這個方法,表示所有只要出現(xiàn)在活動驗證規(guī)則中的屬性都是安全的。

為此,提供一個特別的別名為 safe 的驗證器來申明哪些屬性是安全的不需要被驗證, 如下示例的規(guī)則申明 title 和 description都為安全屬性。

public function rules()
{
  return [
    [['title', 'description'], 'safe'],
  ];
}

非安全屬性

如上所述,yii\base\Model::scenarios() 方法提供兩個用處:定義哪些屬性應被驗證,定義哪些屬性安全。 在某些情況下,你可能想驗證一個屬性但不想讓他是安全的,可在scenarios()方法中屬性名加一個驚嘆號 !。 例如像如下的secret屬性。

public function scenarios()
{
  return [
    'login' => ['username', 'password', '!secret'],
  ];
}

當模型在 login 場景下,三個屬性都會被驗證,但只有 username和 password 屬性會被塊賦值, 要對secret屬性賦值,必須像如下例子明確對它賦值。

$model->secret = $secret;

數(shù)據(jù)導出

模型通常要導出成不同格式,例如,你可能想將模型的一個集合轉成JSON或Excel格式, 導出過程可分解為兩個步驟,第一步,模型轉換成數(shù)組;第二步,數(shù)組轉換成所需要的格式。 你只需要關注第一步,因為第二步可被通用的數(shù)據(jù)轉換器如yii\web\JsonResponseFormatter來完成。

將模型轉換為數(shù)組最簡單的方式是使用 yii\base\Model::attributes 屬性,例如:

$post = \app\models\Post::findOne(100);
$array = $post->attributes;

yii\base\Model::attributes 屬性會返回 所有 yii\base\Model::attributes() 申明的屬性的值。

更靈活和強大的將模型轉換為數(shù)組的方式是使用 yii\base\Model::toArray() 方法, 它的行為默認和 yii\base\Model::attributes 相同, 但是它允許你選擇哪些稱之為字段的數(shù)據(jù)項放入到結果數(shù)組中并同時被格式化。 實際上,它是導出模型到 RESTful 網(wǎng)頁服務開發(fā)的默認方法,詳情請參閱響應格式.

字段

字段是模型通過調用yii\base\Model::toArray()生成的數(shù)組的單元名。

默認情況下,字段名對應屬性名,但是你可以通過覆蓋 yii\base\Model::fields() 和/或 yii\base\Model::extraFields() 方法來改變這種行為, 兩個方法都返回一個字段定義列表,fields() 方法定義的字段是默認字段,表示toArray()方法默認會返回這些字段。extraFields()方法定義額外可用字段,通過toArray()方法指定$expand參數(shù)來返回這些額外可用字段。 例如如下代碼會返回fields()方法定義的所有字段和extraFields()方法定義的prettyName and fullAddress字段。

$array = $model->toArray([], ['prettyName', 'fullAddress']);
可通過覆蓋 fields() 來增加、刪除、重命名和重定義字段,fields() 方法返回值應為數(shù)組, 數(shù)組的鍵為字段名,數(shù)組的值為對應的可為屬性名或匿名函數(shù)返回的字段定義對應的值。 特使情況下,如果字段名和屬性定義名相同,可以省略數(shù)組鍵,例如:

// 明確列出每個字段,特別用于你想確保數(shù)據(jù)表或模型屬性改變不會導致你的字段改變(保證后端的API兼容).
public function fields()
{
  return [
    // 字段名和屬性名相同
    'id',

    // 字段名為 "email",對應屬性名為 "email_address"
    'email' => 'email_address',

    // 字段名為 "name", 值通過PHP代碼返回
    'name' => function () {
      return $this->first_name . ' ' . $this->last_name;
    },
  ];
}

// 過濾掉一些字段,特別用于你想繼承父類實現(xiàn)并不想用一些敏感字段
public function fields()
{
  $fields = parent::fields();

  // 去掉一些包含敏感信息的字段
  unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);

  return $fields;
}

警告:由于模型的所有屬性會被包含在導出數(shù)組,最好檢查數(shù)據(jù)確保沒包含敏感數(shù)據(jù), 如果有敏感數(shù)據(jù),應覆蓋 fields() 方法過濾掉,在上述列子中,我們選擇過濾掉 auth_key, password_hash and password_reset_token。
最佳實踐

模型是代表業(yè)務數(shù)據(jù)、規(guī)則和邏輯的中心地方,通常在很多地方重用, 在一個設計良好的應用中,模型通常比控制器代碼多。

歸納起來,模型:

  • 可包含屬性來展示業(yè)務數(shù)據(jù);
  • 可包含驗證規(guī)則確保數(shù)據(jù)有效和完整;
  • 可包含方法實現(xiàn)業(yè)務邏輯;
  • 不應直接訪問請求,session和其他環(huán)境數(shù)據(jù),這些數(shù)據(jù)應該由控制器傳入到模型;
  • 應避免嵌入HTML或其他展示代碼,這些代碼最好在 視圖中處理;
  • 單個模型中避免太多的場景.

在開發(fā)大型復雜系統(tǒng)時應經(jīng)常考慮最后一條建議, 在這些系統(tǒng)中,模型會很大并在很多地方使用,因此會包含需要規(guī)則集和業(yè)務邏輯, 最后維護這些模型代碼成為一個噩夢,因為一個簡單修改會影響好多地方, 為確保模型好維護,最好使用以下策略:

定義可被多個 應用主體 或 模塊 共享的模型基類集合。 這些模型類應包含通用的最小規(guī)則集合和邏輯。
在每個使用模型的 應用主體 或 模塊中, 通過繼承對應的模型基類來定義具體的模型類,具體模型類包含應用主體或模塊指定的規(guī)則和邏輯。
例如,在高級應用模板,你可以定義一個模型基類common\models\Post, 然后在前臺應用中,定義并使用一個繼承common\models\Post的具體模型類frontend\models\Post, 在后臺應用中可以類似地定義backend\models\Post。 通過這種策略,你清楚frontend\models\Post只對應前臺應用,如果你修改它,就無需擔憂修改會影響后臺應用。

您可能感興趣的文章:

  • 詳解PHP的Yii框架中自帶的前端資源包的使用
  • 簡介PHP的Yii框架中緩存的一些高級用法
  • 深入解析PHP的Yii框架中的緩存功能
  • PHP的Yii框架中View視圖的使用進階
  • PHP的Yii框架中創(chuàng)建視圖和渲染視圖的方法詳解
  • 詳解PHP的Yii框架中的Controller控制器
  • PHP的Yii框架中移除組件所綁定的行為的方法
  • PHP的Yii框架中行為的定義與綁定方法講解
  • 深入講解PHP的Yii框架中的屬性(Property)
  • 詳解PHP的Yii框架中擴展的安裝與使用

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1117073.htmlTechArticlePHP的Yii框架中Model模型的學習教程,yiimodel 模型是 MVC 模式中的一部分, 是代表業(yè)務數(shù)據(jù)、規(guī)則和邏輯的對象。 模型是 CModel 或其子類的實...
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

See all articles