经过多次尝试后,我无法让我的其余功能在我的测试应用程序中运行。
我想知道是否有人对 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 serialize
、json
、amf
和 xml
,我使用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/