簡單的答案;使用此:
$this->{$this->modelBName}->find('all');
請注意屬性名稱周圍的大括號{}。更多的信息可以在手冊中找到;
http://php.net/manual/en/language.variables.variable.php
的清潔器的方法可能是一種「工廠」的方法的;
/**
* Load and return a model
*
* @var string $modelName
*
* @return Model
* @throws MissingModelException if the model class cannot be found.
*/
protected function model($modelName)
{
if (!isset($this->{$modelName})) {
$this->loadModel($modelName);
}
return $this->{$modelName};
}
可以這樣使用;
$result = $this->model($this->modelBName)->find('all');
debug($result);
而且,如果你不想指定模型,但希望它返回一個「$這個 - > modelBName」自動;
/**
* Load and return the model as specified in the 'modelBName' property
*
* @return Model
* @throws MissingModelException if the model class cannot be found.
*/
protected function modelB()
{
if (!isset($this->{$this->modelBName})) {
$this->loadModel($this->modelBName);
}
return $this->{$this->modelBName};
}
這可以這樣使用:
$result = $this->modelB()->find('all');
debug($result);
嘿,大括號工作。不過,我想知道,如果這是一個很好且常見的做法?我還沒有看到任何其他人的代碼這樣做。他們總是在需要使用模型的地方執行'$ this-> ModelName-> someFunction'。任何想法? – musicliftsme 2013-02-11 17:48:51
如果您使用常規'$ uses'數組,則該模型將被加載,您不必手動加載模型。我真的沒有看到使用模型名稱的優勢。海事組織甚至會讓它不太「顯而易見」你正在研究的模型。例如。調用$ this-> User-> save()比$ this - > {$ this-> modelName} - > save()清晰得多。 – thaJeztah 2013-02-11 20:00:37
我現在只是在控制器動作中使用'loadModel('model_name')',而不是使用'$ uses'數組,因爲不是每個動作都需要控制器中使用的整個模型集。我想我會隨着這一個的可讀性去採取你的建議。 – musicliftsme 2013-02-11 21:16:04