Yii 模型
模型是代表业务逻辑和规则的对象。要创建模型,您应该扩展 yii \ base \ Model 类或其子类。
属性
属性表示业务数据。它们可以像数组元素或对象属性一样访问。每个属性都是模型的可公开访问的属性。要指定模型拥有哪些属性,您应该覆盖 yii \ base \ Model :: attributes() 方法。
让我们看看基本应用程序模板的 ContactForm 模型。
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* ContactForm is the model behind the contact form.
*/
class ContactForm extends Model {
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* @return array the validation rules.
*/
public function rules() {
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
/**
* @return array customized attribute labels
*/
public function attributeLabels() {
return [
'verifyCode' => 'Verification Code',
];
}
/**
* Sends an email to the specified email address using the information
collected by this model.
* @param string $email the target email address
* @return boolean whether the model passes validation
*/
public function contact($email) {
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();
return true;
}
return false;
}
}
?>
第1步 -创建一个名为功能 actionShowContactModel 在 SiteController 用下面的代码。
public function actionShowContactModel() {
$mContactForm = new \app\models\ContactForm();
$mContactForm->name = "contactForm";
$mContactForm->email = "user@gmail.com";
$mContactForm->subject = "subject";
$mContactForm->body = "body";
var_dump($mContactForm);
}
在上面的代码中,我们定义 ContactForm 模型,设置属性并在屏幕上显示模型。
第2步 - 现在,如果您 在Web浏览器的地址栏中输入 http:// localhost:8080 / index.php?r = site / show-contact-model ,您将看到以下内容。

如果您的模型从 yii \ base \ Model 扩展而来,则其所有成员变量(公共和非静态)都是属性。 ContactForm 模型中有五个属性- 名称,电子邮件,主题,正文, verifyCode ,您可以轻松添加新的属性。
属性标签
您经常需要显示与属性相关的标签。默认情况下,属性标签由 yii \ base \ Model :: generateAttributeLabel() 方法自动生成。要手动声明属性标签,您可以覆盖 yii \ base \ Model :: attributeLabels() 方法。
步骤1 - 如果您打开 http:// localhost:8080 / index.php?r =网站/联系人, 您将看到以下页面。

请注意,属性标签与其名称相同。
第2步 - 现在, 按照以下方式修改 ContactForm 模型中的 attributeLabels 函数。 **
public function attributeLabels() {
return [
'name' => 'name overridden',
'email' => 'email overridden',
'subject' => 'subject overridden',
'body' => 'body overridden',
'verifyCode' => 'verifyCode overridden',
];
}
第3步 - 如果您 再次打开 http:// localhost:8080 / index.php?r =站点/联系人 ,您会注意到标签已更改,如下图所示。

方案
您可以在不同的场景中使用模型。例如,当客人想要发送联系表单时,我们需要所有的模型属性。当用户想要做同样的事情时,他已经登录了,所以我们不需要他的名字,因为我们可以很容易地从数据库中获取它。
为了声明场景,我们应该重写 场景() 函数。它返回一个数组,其键是场景名称,值是 活动属性 。活动属性是要验证的属性。他们也可以 大规模分配 。
步骤1 - 按以下方式修改 ContactForm 模型。
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* ContactForm is the model behind the contact form.
*/
class ContactForm extends Model {
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
const SCENARIO_EMAIL_FROM_GUEST = 'EMAIL_FROM_GUEST';
const SCENARIO_EMAIL_FROM_USER = 'EMAIL_FROM_USER';
public function scenarios() {
return [
self::SCENARIO_EMAIL_FROM_GUEST => ['name', 'email', 'subject',
'body', 'verifyCode'],
self::SCENARIO_EMAIL_FROM_USER => ['email' ,'subject', 'body',
'verifyCode'],
];
}
/**
* @return array the validation rules.
*/
public function rules() {
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
/**
* @return array customized attribute labels
*/
public function attributeLabels() {
return [
'name' => 'name overridden',
'email' => 'email overridden',
'subject' => 'subject overridden',
'body' => 'body overridden',
'verifyCode' => 'verifyCode overridden',
];
}
/**
* Sends an email to the specified email address using the information
collected by this model.
* @param string $email the target email address
* @return boolean whether the model passes validation
*/
public function contact($email) {
if ($this -> validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();
return true;
}
return false;
}
}
?>
我们添加了两个场景。一个用于客户,另一个用于认证用户。当用户通过认证时,我们不需要他的名字。
第2步 - 现在,修改 SiteController 的 actionContact 功能。 **
public function actionContact() {
$model = new ContactForm();
$model->scenario = ContactForm::SCENARIO_EMAIL_FROM_GUEST;
if ($model->load(Yii::$app->request->post()) && $model->
contact(Yii::$app->params ['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
第3步 - 在Web浏览器中键入 http:// localhost:8080 / index.php?r =站点/联系人 。您会注意到目前所有的模型属性都是必需的。

第4步 - 如果您更改 actionContact中 模型的场景,如以下代码中所示,您将发现name属性不再需要。
$model->scenario = ContactForm::SCENARIO_EMAIL_FROM_USER;

大规模的作业
大量赋值是通过一行代码从多个输入属性创建模型的便捷方式。
代码行是 -
$mContactForm = new \app\models\ContactForm;
$mContactForm->attributes = \Yii::$app->request->post('ContactForm');
上面给出的代码行相当于 -
$mContactForm = new \app\models\ContactForm;
$postData = \Yii::$app->request->post('ContactForm', []);
$mContactForm->name = isset($postData['name']) ? $postData['name'] : null;
$mContactForm->email = isset($postData['email']) ? $postData['email'] : null;
$mContactForm->subject = isset($postData['subject']) ? $postData['subject'] : null;
$mContactForm->body = isset($postData['body']) ? $postData['body'] : null;
前者更清洁。注意, 大规模分配 仅适用于 安全属性 。它们只是 scenario() 函数中列出的当前方案属性。
数据导出
模型通常需要以不同的格式导出。该模型转换为数组,修改 actionShowContactModel 的功能 SiteController -
public function actionShowContactModel() {
$mContactForm = new \app\models\ContactForm();
$mContactForm->name = "contactForm";
$mContactForm->email = "user@gmail.com";
$mContactForm->subject = "subject";
$mContactForm->body = "body";
var_dump($mContactForm->attributes);
}
在地址栏中键入 http:// localhost:8080 / index.php?r = site / show-contact-model ,您将看到以下内容 -

要将模型转换为 JSON 格式,请按以下方式修改 actionShowContactModel 函数 -
public function actionShowContactModel() {
$mContactForm = new \app\models\ContactForm();
$mContactForm->name = "contactForm";
$mContactForm->email = "user@gmail.com";
$mContactForm->subject = "subject";
$mContactForm->body = "body";
return \yii\helpers\Json::encode($mContactForm);
}
浏览器输出 -
{
"name":"contactForm",
"email":"user@gmail.com",
"subject":"subject",
"body":"body ",
"verifyCode":null
}
重点
在精心设计的应用程序中,模型通常比控制器快得多。模型应该 -
- 包含业务逻辑。
- 包含验证规则。
- 包含属性。
- 不嵌入HTML。
- 不直接访问请求。
- 没有太多场景。
下一章:Yii Widgets
一个小部件是一个可重用的客户端代码,其中包含HTML,CSS和JS。此代码包含最少的逻辑,并封装在 yii \ base \ Widget对象中。我们可以在任何视图中轻松插入和应用此对象。第1步 - 要查看小部件,请 ...
AI 中文社