如何在主控主模型中生成函数yii2模型

时间:2017-01-10 20:40:05

标签: inheritance model-view-controller yii2 extend

我正在使用yii2高级应用程序,我创建了一个主模型,我的目标是创建子模型的相同功能,并将它们放入主模型中,以便自动生成而无需返回到gii工具。 我这样开始:

<?php

namespace common\components;

use Yii;

class BaseModel extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return  '{{%'.Yii::$app->controller->id.'}}';
    }

    public function rules()
    {       

    }

    public function attributesLabels()
    {       

    }
    ...etc
}

任何想法如何生成rules()和attributeLabels()函数? 我认为它和发电机一样,但我不知道如何开始。

2 个答案:

答案 0 :(得分:1)

在Yii2中这样做并不是一个好主意。我的意思是,如果你使用来自非User的控制器的UserController模型,你将引用一个与它无关的表。

例如,当您尝试使用默认的User控制器/操作登录您的网站时使用相同的site/login模型类,您的User模型会尝试找到您的用户尝试使用site表登录。它会崩溃并燃烧。

rules()方法也是如此。如果您需要添加无法从数据库表中获取的验证规则,并且需要由程序员为模型定义,则有一些选项。

对于某些情况,当您的特定要求与您尝试的操作相符时,这似乎是一个好主意,但这是一个非常糟糕的做法。

答案 1 :(得分:0)

您可以手动添加

<?php

namespace common\models;//Change it, that's correct one

use Yii;

class BaseModel extends \yii\db\ActiveRecord

{

   public static function tableName()
   {
       return  '{{%'.Yii::$app->controller->id.'}}';
   }

   public function rules()
   {       
      return [
          // some base rules
          [['name', 'email', 'subject', 'body'], 'required'],
      ];
   }

   public function attributeLabels()
   {
       //Some dummy labels
       return [
           'name' => 'Your name',
           'email' => 'Your email address',
           'subject' => 'Subject',
           'body' => 'Content',
       ];
   }
    ...etc
}

您实际上可以删除rules()attributeLabels(),以便动态传递(规则将为空)和属性,如文档中所述, By default, attribute labels are automatically generated from attribute names. The generation is done by the method yii\base\Model::generateAttributeLabel(). It will turn camel-case variable names into multiple words with the first letter in each word in upper case. For example, username becomes Username, and firstName becomes First Name. Link to it.

或者,如果您想要,您可以在Base模型中添加一些基本人员,然后在您的子模型中完成剩下的工作 像这样:

<?php

namespace frontend\models;

use Yii;
use common\models\BaseModel;
use yii\helpers\ArrayHelper;

class BaseModel extends BaseModel

{
   public function rules()
   {
       //Get you base model rules, there will be only those
       //that are acceptable for all of your models
       $rules = parent::rules();
       //merge them with new ones, in this example
       //we have property `group` with `string` validator
       //if you want to override your basic rules pass it as second
       //param
       return ArrayHelper::merge($rules, [[['group'], 'string']]);
   }

   public function attributeLabels()
   {
       //same is here
       $attributeLabels = parent::attributeLabels();
       return ArrayHelper::merge($attributeLabels, ['group' => 'Group name']);

      // OR (use only one) for only new once
      $attributeLabels = parent::attributeLabels();
      $attributeLabels['group'] = 'Some new name';
      return $attributeLabels;
   }
    ...etc
}

如果您有其他问题或有任何不可理解的内容,请与我们联系。