After numerous attempts i can't get my rest functionality to work within my test application.
I wondered if anyone has experience with the RestfulController class in Zend FrameWork 2.0.0beta3.
I implemented the methods from the RestfulController abstract class, let the getList() method echo "Foo", did a curl request to get some output but all i keep getting is a blank screen.
I know there are options for zend framework 1.x but for my project i'm required to use 2.x.
If one of you could offer me some help that would be much appreciated!
I am working on same type of apps and so far it working pretty OK
Routing:
'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:
'alias' => array(
'index' => 'Rest\Controller\IndexController',
...
)
in Controller, type of content that you return for rendering depend on your own strategy, it can be achieved in different ways.
In my case, it need to be able to response in various format such as: php serialize
, json
, amf
and xml
, I use Zend\Serializer\Adapter
to serialize my content and directly return response instance, either you return it directly in controller action or centralized it by trapping RestfulController's dispatch event and return it via callback handler.
Quick Overview:
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 ...
}
}
also don't forget to register your module in application config
I can't tell how you implemented it with the current information but Restful should work just fine with ZF2. I had it working in beta2.
You can also take a look at the ZF2 Restful Module Skeleton on GitHub for inspiration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With