上QQ阅读APP看书,第一时间看更新
Using 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 base controller is possible and can be useful.
Getting ready
A new application using yiic webapp
is to be set up.
Let's say we want to add some controllers that will be accessible only when the user is logged in. We can surely set this constraint for each controller separately, but we will do it in a better way.
How to do it...
- First, we will need a base controller that our user-only controllers will use. Let's create
SecureController.php
inprotected/components
with the following code:<?php class SecureController extends Controller { public function filters() { return array( 'accessControl', ); } public function accessRules() { return array( array('allow', 'users'=>array('@'), ), array('deny', 'users'=>array('*'), ), ); } }
- Now, go to the Gii controller generator and enter
SecureController
into theBase Class
field. You will get something like this:class TestController extends SecureController { public function actionIndex() { $this->render('index'); } … }
- Now, your
TestController
index will be only accessible if the user is logged in, even though we have not declared it explicitly in theTestController
class.