开发者

CakePHP changing virtual fields at runtime

I have a Product model for a multi site application.

Depending on the domain(site) I want to load different data.

For example instead of having a name and description fields in my database I have posh_name, cheap_name, posh_description, and cheap_description.

if I set something up like this:

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

Then it always works, whether accessed directly from the model or via association.

But I need the virtual fields to be different depending on the domain. So first I creating my 2 sets:

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

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

So these are my 2 sets, but how do I assign the correct one based on domain? I do have a global function called isCheap() that lets me know if I am on the lower end domain or not.

so I tried this:

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

This gives me an error. Apparently you cannot assign variables in a Class definition like this.

So I put this in my Product model instead:

function开发者_如何学编程 beforeFind($queryData)
{
    $this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;

    return $queryData;
}

This works ONLY when the data is accessed directly from the model, DOES NOT work when the data is accessed via model association.

There has got to be a way to get this to work right. How?


Well if I put it in the constructor instead of the beforeFind callback it seems to work:

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;
    }
}

However, I am not sure if this is a CakePHP no no that can come back to bite me?


seems like the issue could be that the model association is a model that is built on the fly. eg AppModel

try and do pr(get_class($this->Relation)); in the code and see what the output is, it should be your models name and not AppModel.

also try and use:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜