Yii 2.0: Optimize Scenarios for yii2

1 follower

Working with scenarios, with models that can receive many modifications in their rules or structures as development evolves, can create disruptions in the rescue process.

One way to avoid this disorder is to encapsulate the information defined for the scenarios and to have a single point of customization.

For this we need to create constants for each scenario, note: once you define a scenario, you will need to use scenarios for any database edition that uses this model.

In model

class MyModel extends \yii\db\ActiveRecord
{
 
  const SCENARIOCRIATE = 'scenariocriate';
  const SCENARIOUPDATE = 'scenarioupdate';
 
    // scenarios encapsulated
    public function getCustomScenarios()
    {
 
      return [
          self::SCENARIOCRIATE      =>  ['user_id', 'name', 'desc', 'published','date_create'],
          self::SCENARIOUPDATE      =>  ['user_id', 'name', 'desc', 'date_update'],
      ];
    }
    // get scenarios
    public function scenarios()
    {
        $scenarios = $this->getCustomScenarios();
        return $scenarios;
    }
 
    // modify itens required for rules
    public function ModifyRequired()
    {
 
      $allscenarios = $this->getCustomScenarios();
      // published not required
      $allscenarios[self::SCENARIOCRIATE] = array_diff($allscenarios[self::SCENARIOCRIATE], ['published']);
      return $allscenarios;
 
    }
 
    public function rules()
    {
      // get scenarios
      $allscenarios = $this->ModifyRequired();
        return [
            [$allscenarios[self::SCENARIOCRIATE], 'required', 'on' => self::SCENARIOCRIATE],
            [$allscenarios[self::SCENARIOUPDATE], 'required', 'on' => self::SCENARIOUPDATE],
            [['user_id'], 'integer'],
            [['name','desc'], 'string', 'max' => 70],
            [['date_create', 'date_update'], 'date', 'format' => 'php:Y-m-d H:i:s'],
        ];
    }

O getCustomScenarios será usado para quando for necessário fazer modificações de colunas.

O ModifyRequired é utilizado para remover do required, pois neste momento será utilizado getCustomScenarios para o save.

In Controller

public function actionIndex()
{
 
    $model = new MyModel;
    $model->scenario = 'scenariocriate';
 
    if ($model->load(\Yii::$app->request->post())){
       // get all scenarios
        $allscenarios=$model->getCustomScenarios();
        // force my columns
        if($model->save(true, $allscenarios[$this->scenario])){
          //return true
        } 
    }
}

It may seem redundant, but constructing the controller in this way, avoids having problems with maintenance of database tables, the adjustments will be made only in the model, since there is no reference of communes in the controller.

Be the first person to leave a comment

Please to leave your comment.

Write new article