0

可以将例如 json 上下文添加到特定操作:

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

但是如果我想将 jsonContext 添加到当前控制器中的两个或所有操作中呢?我试过了:

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

但没有结果。我知道我可以使用:

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

但我正在寻找更原始的解决方案。先感谢您。

4

3 回答 3

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()
    ;

通过这样做,“帮助”上下文可用于我的控制器中的每个操作。

这些样本尚未经过全面测试,当然也不是完美的,但它们是解决问题的良好起点。

于 2012-09-19T07:38:27.850 回答
1

好吧,你的第二个版本是错误的,你的第三个版本是矫枉过正的。

我通常是这样做的:

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

如果这对您来说还不够,您可以遍历所有操作并将它们添加到上下文中。

于 2011-10-03T07:08:00.977 回答
1

要将上下文添加到所有操作,您可以将其放入控制器的 init 中:

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

只要您不使用转发或重定向,这就会起作用,因为它将上下文添加到当前操作。

于 2014-09-09T10:49:04.683 回答