2011-10-03 38 views
0

有posibility添加例如JSON上下文的具體行動:如何上下文添加到整個控制器zendFramework

$this->_helper->ajaxContext() 
    ->addActionContext('index', 'json') 
    ->initContext(); 

,但怎麼樣,如果我想jsonContext添加兩個或電流​​控制器的所有動作; 我tryed:

$this->_helper->ajaxContext() 
    ->addActionContext(array('index', 'second'), 'json') 
    ->initContext(); 

,但沒有結果。 我知道我可以使用:

$this->_helper->ajaxContext() 
    ->addActionContext('index', 'json') 
    ->initContext(); 
$this->_helper->ajaxContext() 
    ->addActionContext('second', 'json') 
    ->initContext(); 

但我期待更多的原創解決方案。 預先感謝您。

回答

1

那麼,你的第二個版本是錯誤的,你的第三個版本是矯枉過正。

這是怎麼了,我通常做:

$this->_helper->ajaxContext() 
    ->addActionContext('index', 'json') 
    ->addActionContext('second', 'json') 
    ->initContext(); 

如果這是不夠的,你可以通過所有的動作循環,並將其添加到上下文。

2

我知道這是一個老問題,但如果其他人正在尋找解決方案,我認爲繼承Zend_Controller_Action_Helper_ContextSwitch是一種方法。

就我而言,我的子類,以便它認爲「*」作爲通配符「一切行動」:

class My_Controller_Action_Helper_ContextSwitch extends Zend_Controller_Action_Helper_ContextSwitch { 
/** 
* Adds support logic for the "*" wildcard. 
* 
* @see Zend_Controller_Action_Helper_ContextSwitch::getActionContexts() 
*/ 
public function getActionContexts($action = null) { 
    $parentContexts = parent::getActionContexts($action = null); 

    $contextKey = $this->_contextKey; 
    $controller = $this->getActionController(); 

    if (isset($controller->{$contextKey}['*'])) { 
     $contexts = $controller->{$contextKey}['*']; 
    } 
    else { 
     $contexts = array(); 
    } 

    return array_merge($parentContexts, $contexts); 
} 

/** 
* Adds support logic for the "*" wildcard. 
* 
* @see Zend_Controller_Action_Helper_ContextSwitch::hasActionContext() 
*/ 
public function hasActionContext($action, $context) {  
    if (!$result = parent::hasActionContext($action, $context)) { 
     $controller = $this->getActionController(); 
     $contextKey = $this->_contextKey; 

     $contexts = $controller->{$contextKey}; 

     foreach ($contexts as $action => $actionContexts) { 
      foreach ($actionContexts as $actionContext) { 
       if ($actionContext == $context && $action == '*') { 
        return true; 
       } 
      } 
     } 
    } 

    return $result; 
} 

}

而在我的控制,我用下面的語法設置環境切換:

$contextSwitch = $this->_helper->getHelper('contextSwitch'); 
    $contextSwitch 
     ->addActionContext('*', array('help')) 
     ->initContext() 
    ; 

通過這樣做,「幫助」上下文可用於我的控制器中的每個操作。

這些樣品尚未經過充分測試,當然不是完美的,但它們是解決問題的良好起點。

1

爲背景添加到所有的行動,你可以把這個到你的控制器的初始化:

$contextSwitch = $this->_helper->getHelper('contextSwitch'); 
$action = $this->getRequest()->getActionName(); 
$contextSwitch->addActionContext($action, 'pdf') 
       ->initContext(); 

這個工作,只要你不使用轉發或重定向,因爲它增加的背景下當前的操作。

相關問題