使用控制器插件来扩展zend框架中的现有布局


Using a controller plugin to extend the existing layout in zend framework

我有一个布局文件如下:

<?php echo $this->doctype(); ?>
<html>
    <head>
        <?php echo $this->headTitle(); ?>
        <?php echo $this->headLink(); ?>
    </head>
    <body>
        <?php echo $this->layout()->content; ?>
    </body>
</html>

我有一个用另一个模板编写的菜单系统

<p>
    <div>
        menu code goes here
    </div>
    <p>
        <?php echo $this->actionContent; ?>
    </p>
</p>

我希望操作方法的输出应该放在$this->actionContent中,所有这些都应该放在布局中。

然后我写了一个控制器插件如下:

class ZFExt_Controller_Plugin_Addmenu extends Zend_Controller_Plugin_Abstract 
{
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $view = Zend_Controller_Front::getInstance()
                      ->getParam('bootstrap')
                      ->getResource('view');
        if (false !== $request->getParam('menu'))
        {
            $response = $this->getResponse();
            $content = $response->getBody(true);
            $view->menuContent = $content['default'];
            $updatedContent = $view->render('menu.phtml');
            $response->setBody($updatedContent);
        }
    }
}

在控制器类中

class IndexController extends Zend_Controller_Action {

    public function indexAction() {
    }
    public function viewAction()
    {
          $this->getRequest()->setParam('menu', false);
    }
}

因此,无论哪个操作不需要菜单,我们都可以传递一个值为"false"的参数"menu"。

我的问题是:这样做对吗?

首先,我可能不会从操作中呈现菜单。我倾向于将操作视为对应于HTTP请求,为等待的客户端构建完整的页面/响应,而不仅仅是页面片段。我要么有一个单独的类/组件句柄菜单创建,要么只使用Zend_Navigation

除此之外,如果我理解正确,你只想让每个动作都能启用/禁用布局的菜单部分,对吧?

那么,简单地在视图中设置一个开关来启用/禁用布局中的菜单如何。

布局看起来像:

<?php echo $this->doctype(); ?>
<html>
    <head>
        <?php echo $this->headTitle(); ?>
        <?php echo $this->headLink(); ?>
    </head>
    <body>
        <?php if ($this->renderMenu): ?>
            // render menu here 
        <?php endif; ?>
        <?php echo $this->layout()->content; ?>
    </body>
</html>

然后在你的操作中,如果你想禁用菜单渲染,你可以设置:

$this->view->renderMenu = false;

在请求调度周期的某个时刻为$view->renderMenu标志设置一个默认值可能也是值得的——可能是在引导程序中,或者在控制器插件中,或者控制器init()中。

相关文章: