2013-05-29 38 views
2

我使用Propel和CodeIgniter一起使用。我做了一個MY_Model類(它擴展了CI_Model),它使用它的構造函數加載Propel。在擴展類中使用名稱空間

如果你很好奇:

class MY_Model extends CI_Model{ 
    public function __construct(){ 
     parent::__construct(); 

     require_once '/propel/runtime/lib/Propel.php'; 
     Propel::init('/build/conf/project-conf.php'); 
     set_include_path('/build/classes'.PATH_SEPARATOR.get_include_path()); 
    } 
} 

所以,現在當我提出一個新的笨模型,它將裝載的Propel我。事情是,我給一些Propel生成的模型添加了命名空間。我想我可以在模型的構造函數中添加use Reports;行,但不可以。

class Reports_model extends MY_Model{ 
    function __construct(){ 
     parent::__construct(); 
     use Reports; 
    } 
} 

這給了我

syntax error, unexpected T_USE

好吧,我想,讓我們嘗試把它的構造外:

class Reports_model extends MY_Model{ 
    use Reports; 

    function __construct(){ 
     parent::__construct(); 
    } 
} 

現在,我得到一個較長的錯誤:

syntax error, unexpected T_USE, expecting T_FUNCTION

作爲最後的手段,我添加了use Reports;之前的類聲明:

use Reports; 

class Reports_model extends MY_Model{ 
    function __construct(){ 
     parent::__construct(); 
    } 
} 

現在我得到更多的錯誤!

The use statement with non-compound name 'Reports' has no effect
Class 'ReportsQuery' not found

在班級的另一個功能中,我有一個行$report = ReportsQuery::create();

那麼,我怎樣才能得到use Reports;線路的工作?我真的不想加入Reports\無處不在

我怎樣才能使它所以我可以做:的

$report = ReportsQuery::create(); 

代替:

$report = Reports\ReportsQuery::create(); 
+0

好問題...我的後續將是爲什麼PHP不能找到'Reports'命名空間?我的猜測是'Reports_model'類的位置使得PHP不知道在哪裏找到'Reports'。對不起,我不是名字空間專家,但是如果您在這裏沒有得到答案,您可能想在Propel google小組中詢問這個問題! – jakerella

+0

@jakerella:'Reports'命名空間只存在於Propel的模型中。我的猜測是'MY_Model'的構造函數尚未被調用,所以PHP不知道名稱空間在哪裏。 –

+0

Riiiight ... hrm。也許你只需要始終在模型構造函數中初始化Propel?換句話說,把它放在某種啓動區域(不太熟悉CI)。 – jakerella

回答

2

顯然,use關鍵字不會做我所做的事情。這只是告訴PHP在哪裏尋找一個類。

我需要做的就是使用namespace關鍵字來聲明我的類位於Reports命名空間中。然後我必須告訴它從全局名稱空間使用MY_Model

namespace Reports; 
use MY_Model; 

class Reports_model extends MY_Model{ 
    function __construct(){ 
     parent::__construct(); 
    } 
} 

我還可以做class Reports_model extends \MY_Model{代替use MY_Model;線。

現在問題在於CodeIgniter找不到Reports_model,因爲它現在位於Reports名稱空間中,而不是全局名稱空間。我在另一個StackOverflow問題(https://stackoverflow.com/a/14008411/206403)中找到了解決方案。

有一個函數叫做class_alias,它基本上是魔法。

namespace Reports; 
use MY_Model; 

class_alias('Reports\Reports_model', 'Reports_model', FALSE); 

class Reports_model extends MY_Model{ 
    function __construct(){ 
     parent::__construct(); 
    } 
} 

而且,這是完美的!

+0

實際上,您可以在命名空間前添加'\\'並在glbal範圍內訪問它。納耶斯特可能想這樣說。 – itachi

+0

@itachi:我在我的回答中提到:'extends \ MY_Model'。問題是,我使用CodeIgniter,所以我不能編輯它來添加斜線。 –

0

僅僅通過 「\」 前綴的所有類,而命名空間中的代碼與命名空間

+0

但是,如何讓我的代碼在*名稱空間中? *這是這裏的問題。 –

+0

代碼在「命名空間BlahBlahBlah;」將在命名空間BlahBlahBlah。 如果你在那裏定義了一些類,你可以在\ BlahBlahBlah \ MyClass 之外使用該類,或者添加「use BlahBlahBlah \ MyClass;」到它將被使用的文件並通過沒有命名空間的類名訪問它。請注意,在「使用」結構中,您必須指定完整的名稱空間類名,php無法以這種方式導入某些名稱空間的所有類。 如果你在課堂上寫「use」,它會被解釋爲添加特性到這個類中,你不需要它。 – Nayjest

相關問題