[SOLVED] Creating a Parent controller, but isn't found.

Hi,

I’ve started working with Yii, and wanted to ask about how to impliment a parent controller for all the controllers I intend to write.

I found an example of what I want to do explained in the cookbook:

http://www.yiiframework.com/doc/cookbook/54/

I’ve done a simplified version, where I created a new installation of Yii which works perfectly. I created a new “ParentController.php” in “/htdocs/protected/controllers”, which is a basic class which looks like this:


<?php

class ParentController extends CController

{

	public function __construct()

	{

		echo "Test";

	}

}

?>

I then modified the existing SiteController.php class to it extended from ParentController instead of CController, like so:


<?php


class SiteController extends ParentController 	

{

/* etc */

}

?>



All I get though is the following error:

So it appears it can’t find the “ParentController.php”. Having read & tried the example in the cookbook with exactly the same result (in that case, ExampleController can’t find ParentController), can anyone please tell me what I’m doing wrong?

Where should I be putting the "ParentController.php"?

Thanks in advance.


Update: Thanks to Y!! and jayrulez I’ve resolved this. It might be worth updating the tutorial I link to reflect that the parent controllers need to be placed in “/protected/components” and the config updated to allow other components to be loaded from this directory.

Welcome to the forum!

You have to put the parent controller into the components folder (eg /protected/components). If there’s not already an include defined for the components folder, you have to add it to the config:




...


'import' => array(

   'application.components.*',

),


...



you need to import your parent controller.

here’s an example, i create my parent controller

under : protected/components/controllers

i will need to import my parent controller and the most appropriate way for this scenario is to add the alias to the import config in protected/config/main.php like




	// autoloading model and component classes

	'import'=>array(

             'application.components.controllers.*',

             ........



Thank you both for quick & helpful replies! Both approaches work perfectly, and make sense! I just wasn’t sure what the new class was classed as, if you get my meaning. I’ll be using jayrulez’s approach, purely for directory structure consistency.

So now, if I want to run some pre-processing on each page, I can do that in the ParentController, inside a function called init() (instead of __construct, which causes a headache). That’s perfect!

I’ve also managed to figure out how to bind data in the ParentController (using a method in that exact tutorial) that can be used in the sub-controllers view, which makes life very easy for what I want to do.

Thanks again!