Question

class SomeController extends Controller
{

        public function actionIndex() {
                echo 'This is some controller';
        }
}


class AnotherController extends SomeController
{

        public function actionIndex() {
                echo 'This is another controller';
        }
}

This works:

index.php?r=some

but ...

index.php?r=another

says:

PHP warning

include(SomeController.php): failed to open stream: No such file or directory

Both of the files are in

test\protected\controllers\

BTW in the past I also tried using the Gii Controller Generator with "SomeController" as the base class...

It said:

The controller has been generated successfully. You may try it now.

Generating code using template 
"C:\xampp\htdocs\yii\framework\gii\generators\controller\templates\default"...
generated controllers\YetAnotherController.php
generated views\yetAnother\index.php
done!

When I clicked on "try it now" it also said:

PHP warning

include(SomeController.php): failed to open stream: No such file or directory

Was it helpful?

Solution

Edit:

Classes inside protected/controllers are not autoloaded, therefore you'll have to import the parent class file before extending from it:

In AnotherController.php:

Yii::import('application.controllers.SomeController');
public class AnotherController extends SomeController {
    // ...
}

Incase you need to access the base class from url also, you can use the above method. Otherwise you can put your base class inside protected/components as you have already figured out.


Yii autoloading works only when you have the same name for the file as the class that the file contains. Meaning class SomeController should be within SomeController.php file.

Make those changes and it should work.

A helpful wiki: Understanding Autoloading Helper Classes and Helper functions.

Guide link:

Class files should be named after the public class they contain.

OTHER TIPS

To extend any class just go to the config file and add the class in the import section

'import' => array('application.controllers.SomeController')

this will make it available in the entire application without importing explicitly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top