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

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

  1. First, we will need a base controller that our user-only controllers will use. Let's create SecureController.php in protected/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('*'),
                ),
            );
        }
    }
  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.

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.

主站蜘蛛池模板: 阆中市| 韶关市| 土默特右旗| 开阳县| 即墨市| 蛟河市| 阿拉尔市| 南充市| 定西市| 内乡县| 什邡市| 济阳县| 广河县| 阿拉善右旗| 海伦市| 竹山县| 冀州市| 祁门县| 湘乡市| 蒲江县| 灌阳县| 博客| 桐庐县| 四会市| 罗定市| 霍邱县| 淅川县| 龙门县| 威信县| 阿拉善盟| 抚宁县| 灵武市| 靖边县| 屏山县| 莆田市| 通榆县| 西乌珠穆沁旗| 光泽县| 沙河市| 黄陵县| 屏边|