- Yii Application Development Cookbook(Second Edition)
- Alexander Makarov
- 243字
- 2021-11-12 16:36:14
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...
- First, we will need a base controller that our user-only controllers will use. Let's create
SecureController.php
in theprotected/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('*'), ), ); } }
- 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'); } … }
- 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. 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
.
推薦閱讀
- FreeSWITCH 1.2
- 從區塊鏈到Web3:構建未來互聯網生態
- 網絡故障現場處理實踐(第4版)
- 走進物聯網
- Proxmox High Availability
- 網絡安全技術與解決方案(修訂版)
- NB-IoT物聯網技術解析與案例詳解
- C/C++串口通信:典型應用實例編程實踐
- Unity Artificial Intelligence Programming
- jQuery Mobile Web Development Essentials
- 物聯網
- 工業以太網技術:AFDX/TTE網絡原理、接口、互連與安全
- Hands-On Full Stack Web Development with Aurelia
- 移動應用開發技術
- Mastering Prezi for Business Presentations