PHPackages                             blumster/yii2-model-based-controller - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. blumster/yii2-model-based-controller

ActiveYii2-extension[Framework](/categories/framework)

blumster/yii2-model-based-controller
====================================

Base model controller, which automatically loads an ActiveRecord before every call.

0.1.0(10y ago)013BSD-3-ClausePHPPHP &gt;=5.4.0

Since Apr 2Pushed 10y ago1 watchersCompare

[ Source](https://github.com/Blumster/yii2-model-based-controller)[ Packagist](https://packagist.org/packages/blumster/yii2-model-based-controller)[ RSS](/packages/blumster-yii2-model-based-controller/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

Model Based Controller for Yii2
===============================

[](#model-based-controller-for-yii2)

A base controller, which loads an ActiveRecord before every action is ran. (Except, if there is a load exception.)

If you are managing an ActiveRecord class (for this example, a Company), this base controller will load the Company from the database, so it is already available for every action.

You can specify actions, where the ActiveRecord will not be loaded or loading it will be optional. If there is no exception for an action, and the controller couldn't load the model, the controller calls the

```
protected function handleError($error)
{
    return false;
}
```

function, which you can override, and redirect, load a company another way or just display an error message. $error can be BaseModelController::ERROR\_NO\_PARAMETER (no parameter, or null) or BaseModelController::ERROR\_NOT\_FOUND (not found in the ddatabase)

Returning false will give an empty page, true will let framework to continue or

```
$this->redirect([ 'somwhere/nice' ]);
return false;
```

will redirect the invalid request.

You can also specify with or joinWith statements, which is automatically handled by the controller. Use BaseModelController::RELATION\_WITH, if you don't want to add a condition. If you want to, add the condition in the modelLoadQuery($action) (like below) and use BaseModelController::RELATION\_JOIN\_WITH.

Loading the model will setup the ModelUrl class, which is a helper class for creating URLs. You can use the ModelUrl to automatically include the id of the loaded model.

```
Url::to([ 'company/someaction', 'id' =>  ])
```

is equal to

```
ModelUrl::to([ 'company/someaction' ]);
```

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist blumster/yii2-model-based-controller "*"
```

or add

```
"blumster/yii2-model-based-controller": "*"
```

to the require section of your `composer.json` file.

Usage: After install, you can start using it. Example code:

```
use blumster\controller\BaseModelController;

class CompanyController extends BaseModelController
{
    /**
     * @var \app\models\Company|null
     */
    protected $model = null; // Override the BaseModelController::$model, so an IDE (for example: PhpStorm) can make use of the @var  to use the auto-completion feature, this line is only for the auto-completion. It is optional.

    /**
     * @var string
     */
    protected $paramName = 'cid'; // defaults to 'id' in the BaseModelController

    /**
     * @var string
     */
    protected $idColumnName = 'main_id'; // default to 'id' in the BaseModelController

    /**
     * @inheritdoc
     */
    protected static function requiredWiths()
    {
        return [
            'index' => [
                'relation1' => BaseModelController::RELATION_WITH,
                'relation2' => BaseModelController::RELATION_JOIN_WITH
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    protected static function modelLoadExceptions()
    {
        return [
            'list' => BaseModelController::LOAD_SKIP,
            'form' => BaseModelController::LOAD_OPTIONAL
        ];
    }

    /**
     * @inheritdoc
     */
    protected function modelLoadQuery($action)
    {
        $query = Company::find();

        if ($action === 'index') {
            $query->where([ 'relation2.type' => 'test_type' ]); // You can specify extra conditions, based on the action. You must use BaseModelController::RELATION_JOIN_WITH to use the relation's table in the where condition
        }

        return $query;
    }

    /**
     * Magic index action.
     */
    public function actionIndex()
    {
        return $this->render('index', [
            'model' => $this->model,
            'relation1Entries' => $this->model->relation1 // Already loaded (by requiredWiths())
        ]);
    }

    /**
     * Lists the Companies. This is an exception, here we doesn't have the Company, we are listing all of the Companies, so we can select one.
     *
     * @return string
     */
    public function actionList()
    {
        $provider = new ActiveDataProvider([
            'query' => Company::find(),
            'sort' => [
                'attributes' => [ 'name', 'seat', 'enabled' ]
            ],
            'pagination' => [ 'pageSize' => 20 ]
        ]);

        return $this->render('list', [
            'dataProvider' => $provider
        ]);
    }

    /**
     * Handles the creation and update of a Company. In this case, the Company is optional. If we have one, it's an edit form. If we don't, it's a create form.
     *
     * @return array|string|Response
     * @throws \Exception
     */
    public function actionForm()
    {
        $model = null;

        if (!is_null($this->model)) {
            $model = $this->model;
        } else {
            $model = new Company();
        }

        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }

            if ($model->save()) {
                return $this->redirect([ 'company/list' ]);
            } else {
                Yii::error('Unable to save Company! Errors: ' . print_r($model->getErrors(), true));
            }
        }

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

###  Health Score

22

—

LowBetter than 21% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3734d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/568942?v=4)[Blumster](/maintainers/Blumster)[@Blumster](https://github.com/Blumster)

---

Top Contributors

[![Blumster](https://avatars.githubusercontent.com/u/568942?v=4)](https://github.com/Blumster "Blumster (4 commits)")

---

Tags

yii2extensioncontroller

### Embed Badge

![Health badge](/badges/blumster-yii2-model-based-controller/health.svg)

```
[![Health](https://phpackages.com/badges/blumster-yii2-model-based-controller/health.svg)](https://phpackages.com/packages/blumster-yii2-model-based-controller)
```

###  Alternatives

[miloschuman/yii2-highcharts-widget

Highcharts widget for Yii 2 Framework.

1641.6M15](/packages/miloschuman-yii2-highcharts-widget)[skeeks/cms

SkeekS CMS — control panel and tools based on php framework Yii2

13725.7k50](/packages/skeeks-cms)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
