Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - Inheriting From Custom Controller Class - Not Found

Tags:

php

yii

gii

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

like image 768
Luke Wenke Avatar asked Jan 04 '13 02:01

Luke Wenke


1 Answers

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.

like image 151
bool.dev Avatar answered Sep 19 '22 00:09

bool.dev