2013-01-04 29 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