2011-02-23 36 views
1

我有一個多站點應用程序的產品模型。CakePHP在運行時更改虛擬域

根據域(站點)我想加載不同的數據。

例如,而不是在我的數據庫中有一個namedescription字段我有posh_name,cheap_name,posh_description和cheap_description。

如果我設置的東西像這樣:

class Product extends AppModel 
{ 
    var $virtualFields = array(
     'name' => 'posh_name', 
     'description' => 'posh_description' 
    ); 
} 

然後,它始終工作,無論是從模型直接或通過關聯訪問。

但我需要虛擬字段根據域不同而不同。所以,首先我創建我的2臺:

var $poshVirtualFields = array(
    'name' => 'posh_name', 
    'description' => 'posh_description' 
); 

var $cheapVirtualFields = array(
    'name' => 'cheap_name', 
    'description' => 'cheap_description' 
); 

因此,這些都是我的2套,但我怎麼分配基於域正確的?我確實有一個名爲isCheap()的全局函數,讓我知道我是否在低端域。

所以我嘗試這樣的:

var $virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields; 

這給了我一個錯誤。顯然你不能像這樣在類定義中分配變量。

所以我把這個在我的產品型號,而不是:

function beforeFind($queryData) 
{ 
    $this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields; 

    return $queryData; 
} 

這隻有當數據從模型直接訪問,當數據通過模型關聯訪問不起作用。

必須有一種方法才能使其正常工作。怎麼樣?

回答

1

那麼,如果我把它在構造函數中,而不是beforeFind回調似乎工作:

class Product extends AppModel 
{ 
    var $poshVirtualFields = array(
     'name' => 'posh_name', 
     'description' => 'posh_description' 
    ); 

    var $cheapVirtualFields = array(
     'name' => 'cheap_name', 
     'description' => 'cheap_description' 
    ); 

    function __construct($id = false, $table = null, $ds = null) { 
     parent::__construct($id, $table, $ds); 
     $this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields; 
    } 
} 

但是,我不知道這是否是a CakePHP否否那可以回來咬我嗎?

+0

我認爲這只是函數__construct(){},沒有額外的參數。 – Wayne 2011-02-24 05:45:08

+0

@Wayne,實際上API是這樣說的:'當重寫Model :: __ construct()時要小心地包含並且將所有3個參數傳遞給parent :: __構造($ id,$ table,$ ds);'.. 。http://api13.cakephp.org/class/model#method-Model__construct – 2011-02-24 14:01:54

+0

謝謝,我不知道。我已經使用了__construct(){},但沒有發現任何錯誤。 – Wayne 2011-02-25 02:23:48

0

好像問題可能是模型關聯是一個即時建立的模型。例如AppModel

嘗試並做pr(get_class($ this-> Relation));在代碼中看看輸出是什麼,它應該是你的模型名稱而不是AppModel。

也嘗試使用:

var $poshVirtualFields = array(
    'name' => 'Model.posh_name', 
    'description' => 'Model.posh_description' 
); 

var $cheapVirtualFields = array(
    'name' => 'Model.cheap_name', 
    'description' => 'Model.cheap_description' 
);