zend-framework2 - 覆盖特定操作的 View 策略

标签 zend-framework2

我有一个应用程序,我们使用 AbstractRestfulController 和 Json 策略。 (我们对使用这种方法有直接的要求)。所以我们所有的请求都是通过 jQuery Ajax 和 json 完成的。现在我有一个特定的要求,需要下载服务器上存储的pdf文件。我想使用 php/zend header 下载文件,而不是公开文件的实际 http 路径。

对于以下 Restful 方法是否有任何解决方案。我正在考虑针对特定操作的覆盖 View 策略,但不知道如何?

我将有一个针对特定模块使用默认 AbstractActionController 的 final方法,并将我的代码放入其中。但如果它是我拥有的唯一解决方案(因为将当前模块特定代码移动到另一个模块看起来是一个坏主意)?

最佳答案

请参阅下面添加您自己的 View 策略的示例,您可以在文档中查看示例:

http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html

如果您想要这样的话,可以很容易地修改示例来检查给定的 Controller /操作。

<?php
namespace Application;

class Module
{
    public function onBootstrap($e)
    {
        // Register a "render" event, at high priority (so it executes prior
        // to the view attempting to render)
        $app = $e->getApplication();
        $app->getEventManager()->attach('render', array($this, 'registerJsonStrategy'), 100);
    }

    public function registerJsonStrategy($e)
    {
        $app          = $e->getTarget();
        $locator      = $app->getServiceManager();
        $view         = $locator->get('Zend\View\View');
        $phpStrateogy = $locator->get('PhpRendererStrategy');
        // or any you have setup in your config...
        $jsonStrategy = $locator->get('ViewJsonStrategy');

        $routeMatch = $e->getRouteMatch();
        /* @var $routeMatch \Zend\Mvc\Router\RouteMatch */
        $routeName = $routeMatch->getMatchedRouteName();
        if($routeName == 'myroute') {
            // possible change layout?
            //$controller->layout('app/layout/new_layout');
            // Attach strategy, which is a listener aggregate, at high priority
            //$view->getEventManager()->attach($jsonStrategy , 100);
            $view->getEventManager()->attach($phpStrateogy, 1);
        }
    }
}

或者,您可以只返回不同类型的 ViewModel,如果启用了两种策略,您可以通过在 Controller 内返回不同的模型来更改所使用的策略:

public function someAction()
{
    // will use JsonRenderer
    return new \Zend\View\Model\JsonModel(array('bob'));

    // Will use PHPRenderer
    return new \Zend\View\Model\ViewModel(array('bob'));
}

关于zend-framework2 - 覆盖特定操作的 View 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12747622/

相关文章:

php - ZF2中的SQL查询语法错误

session - ZF2中如何实现鉴权

php - ZF2 - 如何插入选择?

mongodb - Zend Framework 2 + Doctrine ODM, "The Class was not found in the chain configured namespaces"错误?

mysql - 在 ZF2 中以 utf-8 格式从数据库中检索数据

php - Zend Framework 2 查询中的双引号

php - 带有对象选择表单的 Doctrine 自定义存储库

php - 使用 PHPxcel 减少数据库插入的执行时间

php - zend framework 2 认证服务

php - ZF2 路由忽略命名空间