jasco-b/view-model

View model for yii2

1.0.2 2020-02-05 12:40 UTC

This package is auto-updated.

Last update: 2024-06-08 05:43:28 UTC


README

View model for Yii2 inspired from laravel view model

Installation

You can install the package via composer:

composer require jasco-b/view-model

Usage

Often in Yii2 or any other frameworks in CRUD`s, it is required from developer use the same data in create and update actions. For instance:

Old Controller

class PostController extends Controller
{
  ...
  
  public function actionCreate() 
  {
      $model = new Post();
      $categories = Categories::find()->all();
      ...
      
      return $this->render('create', [
        'model'         => $model,
        'categories'    => $categories,
      ]);
  }
  
    public function actionUpdate($id) 
    {
      $model = $this->findModel($id);
      $categories = Categories::find()->all();
      ...
      
      return $this->render('update', [
        'model'         => $model,
        'categories'    => $categories,
      ]);
    }

}

As you have seen above, $categoreis has been used in Create and Update action. You can make clean controller and even you can add to view model your comlex logic.

View model

...
use jascoB\ViewModel\ViewModel;

class PostViewModel extends ViewModel
{
    public $model;

    public function __construct($model)
    {
        $this->model = $model;
    }
    
    public function categories()
    {
        return $categories = Categories::find()->all();
    }
}

Controller

class PostController extends Controller
{
  ...
  
  public function actionCreate() 
  {
      $model = new Post();
      ...
      
      return $this->render('create', new PostViewModel($model));
  }
  
    public function actionUpdate($id) 
    {
      $model = $this->findModel($id);
      ...
      
      return $this->render('update', new PostViewModel($model));
    }

}

In order use view model with Yii2 we should change config.php

return [
    'components' => [
        'view'=>[
            'class'=>'jascoB\ViewModel\Classes\View',
        ],
    ],
];