2012-08-09 69 views
0

我想編寫代碼的方式重新使用它:如何保存範圍鏈多次

$chain = Articles::model()->visible()->childOf($teleshow_id); 
echo $chain->count($criteria); 
// 1st echo - will write the amount of visible articles, 
// which are children of $teleshow_id 

echo $chain->count($criteria); 
// this echo will write the amount of all articles 

但我想獲得的echo小號相同的結果。

是否有任何解決方案,以保持$鏈持續存在(不是指針攜手文章::模型() - >可見() - > childOf($ teleshow_id))

+0

我不能說我把你的問題100%,但據我所知,你認爲你需要某種兌現以存儲結果或命名範圍過濾器http://www.yiiframework .com/doc/guide/1.1/en/caching.overview – Nimir 2012-08-09 17:28:55

+0

不,不。這個想法並不是重複同樣的動作次數,而是不止一次地使用$鏈對象的可能性。例如。我做一些像$ chain-> count();然後我做一些分頁操作,然後我做$ chain-> findAll();我不喜歡用所有範圍列表構建新的$鏈類似的對象,將其稱爲findAll方法。 – gl0om 2012-08-09 17:56:45

回答

0

你可以嘗試像的以下:

// in your Articles class 
private $_chain; 

public function getChain($teleshow_id = false) 
{ 
    if(!isset($this->_chain)) 
    { 
     $chain = Articles::model()->visible()->childOf($teleshow_id); 
    } 
    return $this->_chain; 
} 

,然後把它從你的控制器是這樣的:

$model = new Articles(); 
$chain = $model->getChain($teleshow_id); 

$model->chain->count(); 

或類似的東西。如果你想讓你的通話更簡單,你可能需要把getChain變成靜態的,但你應該能夠開始使用。