romi45/yii2-find-model-trait

Trait for Yii2 web controller to find models. Make your web controllers thinner!


Keywords
trait, yii2, findModel, romi45
License
GPL-3.0

Documentation

Trait for Yii2 web controller to find models

Make your web controllers thinner!

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist romi45/yii2-find-model-trait

or add

"romi45/yii2-find-model-trait": "*"

to the require section of your composer.json file.

Usage

Once the trait is installed, you should use it in your web controllers as below:

namespace app\controllers;

use app\models\User;
use romi45\findModelTrait\FindModelTrait;

/**
 * ExampleController implements the CRUD actions for Script model.
 *
 * @method User findModel($id, $class = null) see [[FindModelTrait::findModel()]] for more info
 */
class ExampleController extends CoreController
{
    use FindModelTrait;

    /**
     * @var string Model
     */
    protected $_modelClass = 'app\models\User';


    /**
     * Updates an existing User model.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        return $this->render('update', [
            'model' => $model,
        ]);
    }

}

Or don't specify $_modelClass property in your controller - just pass $model parameter to findModel() method

namespace app\controllers;

use app\models\User;
use romi45\findModelTrait\FindModelTrait;

/**
 * ExampleController implements the CRUD actions for Script model.
 *
 * @method User findModel($id, $class = null) see [[FindModelTrait::findModel()]] for more info
 */
class ExampleController extends CoreController
{
    use FindModelTrait;

    /**
     * Updates an existing User model.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id, 'app\models\User');

        return $this->render('update', [
            'model' => $model,
        ]);
    }

}