If you’re sending raw data to ZF2 over http (perhaps a json document), you can use the “getContent()” method of Zend\Http\PhpEnvironment\Request.
How does this work in practice?
In a controller you might want to do something like this:
1 2 3 4 5 6 7 8 9 | <?php namespace Application\Controller;</code> use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class IndexController extends AbstractActionController { public function indexAction() { $data = $this->getRequest()->getContent(); |
But if you’re always expecting a certain format, say JSON, a controller plugin could give you back the array or object rather than a lot of json_decode calls in your controllers.
The plugin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php namespace My\Mvc\Controller\Plugin; use Zend\Mvc\Controller\Plugin\Params as ZendParams; class Params extends ZendParams { public function fromJson() { $body = $this->getController()->getRequest()->getContent(); if (!empty($body)) { $json = json_decode($body, true); if (!empty($json)) { return $json; } } return false; } } |
And then its as simple as:
1 2 | public function indexAction() { $data = $this->params()->fromJson(); |
Help! Sometimes getContent() doesn’t return my data.
The method uses file_get_contents(‘php://input’) to get the raw data from the HTTP request. Unfortuantely, the php://input stream can only be read once per process. I did have a plug-in that called file_get_contents(‘php://input’) too, and if $request->getContent() gets called after this, it will be empty!
Warning: Declaration of Social_Walker_Comment::start_lvl(&$output, $depth, $args) should be compatible with Walker_Comment::start_lvl(&$output, $depth = 0, $args = Array) in /home/customer/www/arronwoods.com/public_html/blog/wp-content/plugins/social/lib/social/walker/comment.php on line 18
Warning: Declaration of Social_Walker_Comment::end_lvl(&$output, $depth, $args) should be compatible with Walker_Comment::end_lvl(&$output, $depth = 0, $args = Array) in /home/customer/www/arronwoods.com/public_html/blog/wp-content/plugins/social/lib/social/walker/comment.php on line 42
Hello.This article was extremely motivating, especially since I was browsing for thoughts on this issue last couple of days.
You save my life.
After 3 days its work =D
$data = $this->getRequest()->getPost(); it was not working =/
ddddd