2011-02-23 119 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' 
);