我正在开发相同类型的应用程序,到目前为止它运行良好
路由:
'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
快速概览:
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 ...
}
}
也不要忘记在应用程序配置中注册您的模块