php - Zend Framework 2 RESTful Controller 操作

标签 php frameworks zend-framework2

经过多次尝试后,我无法让我的其余功能在我的测试应用程序中运行。

我想知道是否有人对 Zend FrameWork 2.0.0beta3 中的 RestfulController 类有经验。

我实现了 RestfulController 抽象类的方法,让 getList() 方法回显“Foo”,做了一个 curl 请求来获得一些输出,但我一直得到的只是一个空白屏幕。

我知道有适用于 zend 框架 1.x 的选项,但对于我的项目,我需要使用 2.x。

如果你们中的任何一个能给我一些帮助,我将不胜感激!

最佳答案

我正在开发相同类型的应用程序,到目前为止它运行良好

路由:

'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
    'route' => '/[:controller[.:format][/:id]]',
    'constraints' => array(
        'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
        'format' => '(xml|json|sphp|amf)',
        'id' => '[1-9][0-9]*',
    ),
    'defaults' => array(
        'controller' => 'Rest\Controller\IndexController',
        'format' => 'json',
    ),

DI别名:

'alias' => array(
    'index' => 'Rest\Controller\IndexController',
    ...
)

在Controller中,你渲染返回的内容类型取决于你自己的策略,它可以通过不同的方式实现。

在我的例子中,它需要能够以各种格式响应,例如:php serializejsonamfxml,我使用Zend\Serializer\Adapter 序列化我的内容并直接返回响应实例,您可以直接在 Controller 操作中返回它,也可以通过捕获 RestfulController 的调度事件集中它并返回它通过回调处理程序。

快速概览:

namespace Rest\Controller
{
    use Zend\Mvc\Controller\RestfulController;

    class IndexController extends RestfulController
    {
        public function getList()
        {
            $content = array(
                1 => array(
                    'id' => 1,
                    'title' => 'Title #1',
                ),
                2 => array(
                    'id' => 2,
                    'title' => 'Title #2',
                ),
            );
            /**
            * You may centralized this process through controller's event callback handler
            */
            $format = $this->getEvent()->getRouteMatch()->getParam('format');
            $response = $this->getResponse();
            if($format=='json'){
                $contentType = 'application/json';
                $adapter = '\Zend\Serializer\Adapter\Json';
            }
            elseif($format=='sphp'){
                $contentType = 'text/plain';
                $adapter = '\Zend\Serializer\Adapter\PhpSerialize';
            }
            // continue for xml, amf etc.

            $response->headers()->addHeaderLine('Content-Type',$contentType);
            $adapter = new $adapter;
            $response->setContent($adapter->serialize($content));
            return $response;
            }

            // other actions continue ...
    }
}

也不要忘记在应用程序配置中注册您的模块

关于php - Zend Framework 2 RESTful Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9602293/

相关文章:

javascript - 通过ajax将PHP对象返回给javascript

php - 如何在 Prestashop 的产品列表中一次显示含税和不含税的产品价格?

javascript - 如何使用 AngularJs 过滤 JSON 数据?

用于创建 Ajax 网站的 Java 框架(相对于 Web 应用程序)

javascript - Alpaca js可以在ReactJS中使用吗

php - 使用 PHP (Mac) 插入 mySQL 表时出错

php - 如何在 Wordpress 中将 Gravatar 设置为背景图片?

php - 在不同的 GIT 分支上使用 Doctrine 2 迁移是否有任何最佳实践?

php - Zend Framework 2 TableGateway 返回空结果集

php - ZF2 Curl 不发送帖子值