我知道这是一个老问题,但如果其他人正在寻找解决方案,我认为继承 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()
;
通过这样做,“帮助”上下文可用于我的控制器中的每个操作。
这些样本尚未经过全面测试,当然也不是完美的,但它们是解决问题的良好起点。