Yii - 继承自定义控制器类 - 未找到

时间:2013-01-04 02:56:54

标签: 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';
        }
}

这有效:

index.php?r=some

但......

index.php?r=another

表示:

  

PHP警告

     

include(SomeController.php):无法打开流:没有这样的文件或目录

两个文件都在

test\protected\controllers\
过去BTW我也尝试过使用带有“SomeController”的Gii Controller Generator作为基类...

它说:

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!

当我点击“立即尝试”时,它也说:

  

PHP警告

     

include(SomeController.php):无法打开流:没有这样的文件或目录

2 个答案:

答案 0 :(得分:11)

修改

protected / controllers 中的类没有自动加载,因此您必须先导入父类文件,然后才能从中扩展:

AnotherController.php

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

如果你还需要从url访问基类,你可以使用上面的方法。否则,您可以将基类放在 protected / components 中,如您已经想到的那样。


Yii自动加载仅在文件名与文件所包含的类具有相同名称时才有效。含义class SomeController应该在 SomeController.php 文件中。

进行这些更改,它应该有效。

一个有用的维基:Understanding Autoloading Helper Classes and Helper functions

Guide link

  

类文件应该以它们包含的公共类命名。

答案 1 :(得分:3)

要扩展任何类,只需转到配置文件并在导入部分中添加该类

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

这将使其在整个应用程序中可用而无需显式导入。