Using a base controller
In many frameworks, the concept of a base controller that is being extended by other ones is described right in the guide. In Yii, it is not in the guide, as you can achieve flexibility in many other ways. Still, using a base controller is possible and can be useful.
Let's say we want to add some controllers that will be accessible only when the user is logged in. We can certainly set this constraint for each controller separately, but we will do it in a better way.
Getting ready
Create a new application using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-startinstallation.html.
How to do it…
- First, we will need a base controller that our user-only controllers will use. Let's create
@app/components/BaseController.php
with the following code:<?php namespace app\components; use Yii; use yii\web\Controller; use yii\filters\AccessControl; class BaseController extends Controller { public...