官术网_书友最值得收藏!

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.

Getting ready

We are going to set up a new application using yiic webapp.

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...

  1. First, we will need a base controller that our user-only controllers will use. Let's create SecureController.php in the protected/components directory 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('*'),
                ),
            );
        }
    }
  2. Now, go to the Gii controller generator and enter SecureController into the Base Class field. You will get something like this:
    class TestController extends SecureController
    {
        public function actionIndex()
        {
            $this->render('index');
        }
        …
    }
  3. Now, your TestController index will be only accessible if the user is logged in, even though we have not declared it explicitly in the TestController class. You can check it by visiting /index.php?r=test/index while not being logged in.

How it works...

The trick is nothing more than a basic class inheritance. If filters or accessRules is not found in TestController, then it will be called from SecureController.

主站蜘蛛池模板: 平原县| 思南县| 高阳县| 独山县| 建阳市| 民县| 栖霞市| 珠海市| 英吉沙县| 宣汉县| 雷州市| 阜宁县| 沿河| 灵丘县| 同仁县| 仙居县| 渭源县| 太和县| 巴中市| 肇东市| 苍梧县| 山丹县| 霞浦县| 古田县| 红原县| 安达市| 舒城县| 衡东县| 忻城县| 黄平县| 姚安县| 双牌县| 呼图壁县| 塘沽区| 兴国县| 利辛县| 武宁县| 宿迁市| 融水| 陕西省| 衡阳市|