2013-01-04 81 views
5
class SomeController extends Controller 
{ 

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


class AnotherController extends SomeController 
{ 

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

这工作:的Yii - 继承了自定义控制器类 - 找不到

index.php?r=some 

但是......

index.php?r=another 

说:

PHP警告

包括(SomeController.php):未能打开流:没有这样的文件或目录

文件两者都是

test\protected\controllers\ 

顺便说一句,在过去我用GII控制器发生器,还试图“SomeController”作为基类...

它说:

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警告

包括(SomeController.php):未能打开流:没有这样的文件或目录

回答

11

编辑:

类保护/ controllers不是自动加载的,因此您必须先导入父类文件,然后再从其中扩展:

AnotherController.php

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

柜面你需要从URL访问基类也,你可以用上面的方法。否则,您可以将您的基类放在受保护的/组件内,因为您已经想清楚了。


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

进行这些更改,它应该工作。

有用的wiki:Understanding Autoloading Helper Classes and Helper functions

Guide link

类文件应包含的公共类的名字命名。

+0

是的,它在\受保护\ controllers \ SomeController.php BTW就像我说的“http://localhost/yii/testapp/index.php?r =一些”工程...但gii的“YetAnotherController.php”(索引.php?r = yetAnother)和我的“AnotherController.php”(index.php?r = another)给出了它们的基类(SomeController.php)的错误。 SomeController.php的自动加载似乎存在一个问题,当它是基类时,如果我使用index.php?r = some,它可以正常工作。当我在控制器中引用Post.php时,我也遇到同样的错误...它在models/Post.php中... –

+0

哦,那么你会从url访问基本控制器吗?或者它只是一个基类,并且你希望只使用它? –

+0

我想知道我是否可以同时做这两件事? –

3

扩展任何类只要到配置文件,并在进口部

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

这将使其在整个应用程序中提供不导入明确添加类。

+0

谢谢你的提示! – wallerjake