Controller Id And Action


Is it possible to get current controller id and controller action in current controller constructor. I have developed generic function in Controller class which i want to call from child controller class constructor.My objective is to check if user has permission to access controller action e.g view, update action etc.

I have tried with following code but it throws following exception:

[color="#FF0000"][font="Courier New"]PHP Fatal error: Call to a member function getId() on a non-object [/font][/color]

Department Controller

class DepartmentController extends Controller



	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.


	public $layout='//layouts/column2';

	public function __construct() {




Controller Class

class Controller extends CController



	 * @var string the default layout for the controller view. Defaults to '//layouts/column1',

	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.


	public $layout='//layouts/column1';


	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.


	public $menu=array();


	 * @var array the breadcrumbs of the current page. The value of this property will

	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}

	 * for more details on how to specify this property.


	public $breadcrumbs=array();

	public function actionCheckControllPermission() {

		$vUserID = 0;

		$vController = "/".$this->getId();

		$vControllerAction = "/".$this->getAction()->getId();

		if(isset(Yii::app()->user->id)) $vUserID = Yii::app()->user->id;

		$aUserDetail = Common::getUserDetail($vUserID);

// 		Common::PrintR($aUserDetail);

		$vRoleId = $aUserDetail[0]['user_role'];

		if(Common::checkUserPermission($vRoleId, $vController.$vControllerAction)) return true;

		else die("you dont have permission to access this page");



Action is not set at construction time. CController::beforeAction() or a custom filter seems to be a more approriate place to implement your authorization logic.

A few other things to consider:

  • When overriding CController’s constructor keep the original signature and always call parent::__construct() .

  • As a general recommendation, try to avoid calls to complex logic (like authorization) in constructor.

  • Yii provides a built-in toolkit for authentication and authorization. Give it a try before implementing custom solution.

Thanks phtamas. I have call my custom function in beforeAction and it solved my problem.

protected function beforeAction($action)


		if($this->actionCheckControllPermission())	return true;

		return false;