【问题标题】:ZEND Framework 2 RESTful web service template errorZEND Framework 2 RESTful Web 服务模板错误
【发布时间】:2013-09-18 19:44:16
【问题描述】:

您好,当我尝试访问 Zend Framework 2.2.2 项目中的 RESTful Web 服务端点时出现错误。我正在创建一个名为 V1 的模块,但收到以下错误:

Zend\View\Renderer\PhpRenderer::render: Unable to render template "v1/collateral/get-list"; resolver could not resolve to a file

我认为这表明应用程序找不到所需的视图文件。我从this tutorial 开始。我已经搜索了我的问题的答案,并且我发现了其他一些有类似问题的人,但我目前还没有找到我正在寻找的答案,因为我仍然有一个错误。我对 Zend Framework 2 比较陌生,所以对于更有经验的人来说,这可能是一个简单的方法。

这是我迄今为止在路由和视图管理器策略方面所做的工作:

module.config.php:

return array(
'router' => array(
    'routes' => array(
        'collateral' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/v1/collateral[/:id]',
                'constraints' => array(
                    'id'     => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'V1\Controller\Collateral',
                ),
            ),
        ),
    ),
),

'controllers' => array(
    'invokables' => array(
        'V1\Controller\Collateral' => 'V1\Controller\CollateralController',
    ),
),

'view_manager' => array(
    'strategies' => array(
            'ViewJsonStrategy',
    ),
),

);

这是我的控制器代码

Collat​​eralController.php

namespace V1\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;

use V1\Model\Collateral;
//use V1\Form\CollateralForm;
use V1\Model\CollateralTable;
use Zend\View\Model\JsonModel;

class CollateralController extends AbstractRestfulController
{
protected $collateralTable;

public function getList()
{
    $results = $this->getCollateralTable()->fetchAll();
    $data = array();
    foreach($results as $result) {
        $data[] = $result;
    }

    return array('data' => $data);
}

public function get($id)
{
    # code...
}

/*public function create($data)
{
    # code...
}

public function update($id, $data)
{
    # code...
}

public function delete($id)
{
    # code...
}*/

public function getCollateralTable()
{
    if (!$this->collateralTable) {
        $sm = $this->getServiceLocator();
        $this->collateralTable = $sm->get('V1\Model\CollateralTable');
    }
    return $this->collateralTable;
}
}

这里是我的 Module.php 文件

            namespace V1;

            // Add these import statements:
            use V1\Model\Collateral;
            use V1\Model\CollateralTable;
            use Zend\Db\ResultSet\ResultSet;
            use Zend\Db\TableGateway\TableGateway;

            class Module
            {

                public function getAutoloaderConfig()
                {
                    return array(
                        'Zend\Loader\ClassMapAutoloader' => array(
                            __DIR__ . '/autoload_classmap.php',
                        ),
                        'Zend\Loader\StandardAutoloader' => array(
                            'namespaces' => array(
                                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                            ),
                        ),
                    );
                }

                public function getConfig()
                {
                    return include __DIR__ . '/config/module.config.php';
                }

                public function getServiceConfig()
                {
                    return array(
                        'factories' => array(
                            'V1\Model\CollateralTable' =>  function($sm) {
                                $tableGateway = $sm->get('CollateralTableGateway');
                                $table = new CollateralTable($tableGateway);
                                return $table;
                            },
                            'CollateralTableGateway' => function ($sm) {
                                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                                $resultSetPrototype = new ResultSet();
                                $resultSetPrototype->setArrayObjectPrototype(new Collateral());
                                return new TableGateway('collateral', $dbAdapter, null, $resultSetPrototype);
                            },
                        ),
                    );
                }
            }

虽然我不确定根据我在教程中阅读的内容是否需要它,但我创建了以下 empty 视图文件:

\module\V1\view\v1\collateral\get-list.phtml

我想知道这个视图文件是否是必需的,它是否位于正确的位置并正确命名?

对于此错误的任何其他帮助将不胜感激。如果有帮助,我很乐意提供更多信息。

谢谢。

【问题讨论】:

    标签: php rest zend-framework2


    【解决方案1】:

    你说得对,“渲染错误”是因为它找不到你的视图模板,但好消息是你不一定需要一个:

    假设您的 RESTful 服务返回 JSON,请在控制器操作的底部尝试以下操作:

    $result = new \Zend\View\Model\JsonModel($data_you_were_already_returning);
    return $result;
    

    【讨论】:

    • 您对 Web 服务返回 JSON 的假设是正确的。这成功了,我现在在回复中收到了有效的 JSON!再次感谢您的意见。非常感谢!
    • 如何将 JsonModel 设置为默认只返回数据?
    【解决方案2】:

    启用 ViewJsonStrategy 并不意味着响应将 自动返回为 JSON。这意味着如果你返回一个 JsonModel 来自您的控制器,JsonStrategy 将拦截它并 返回 JSON。 (http://zend-framework-community.634137.n4.nabble.com/Returning-JSON-for-404-and-for-exception-td4660236.html)

    所以你需要手动将 ViewModel 替换为 JsonModel

    RestApi\Module.php
    
    public function onBootstrap($e) 
    {    
        $eventManager = $e->getApplication()->getEventManager();        
        $eventManager->attach('render', array($this, 'registerJsonStrategy'), 100);
    }
    
    /**
     * @param  \Zend\Mvc\MvcEvent $e The MvcEvent instance
     * @return void
     */
    public function registerJsonStrategy(\Zend\Mvc\MvcEvent $e) {
        $matches    = $e->getRouteMatch();
        $controller = $matches->getParam('controller');
        if (false === strpos($controller, __NAMESPACE__)) {
            // not a controller from this module
            return;
        }
    
        // Potentially, you could be even more selective at this point, and test
        // for specific controller classes, and even specific actions or request
        // methods.
    
        // Set the JSON model when controllers from this module are selected
        $model = $e->getResult();
    
        if($model instanceof \Zend\View\Model\ViewModel)
        {
            $newModel = new \Zend\View\Model\JsonModel($model->getVariables());
            //$e->setResult($newModel);
            $e->setViewModel($newModel);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多