How to get url parameters in zend framework 2

The snippets in this article show you how to get url parameters in zend framework 2.

In Zend 1 parameters passed through in the url could be retrieved from the request object like so:

$page = $this->getRequest()->getParam('page');

Or to get all params you could use:

$params = $this->getRequest()->getParams();

Getting url parameters in Zend Framework 2

In Zend Framework 2 the parameters are still available via the request object, however you need to use the method specific to the type of parameter you are requesting. For example to get a parameter from a query string you would use the following:

$page = $this->getRequest()->getQuery('page');

The request object also offers the methods for accessing post parameters and files:

  • getPost - from a post parameter
  • getFiles - get posted files

If you want to get all variables, simply don't pass in any parameters:

$params = $this->getRequest()->getQuery();

...and if you'd like this in array format:

$params = $this->getRequest()->getQuery()->toArray();

Alternatively, you can use the 'Params' plugin to access variables like so:

$page = $this->params()->fromQuery('page');

Note this is different than getting parameters from the route (e.g. configured as /page/2/ rather than ?page=2), which would you retrieve like so:

$page = $this->params()->fromRoute('page');

The params plugin provides the following methods for the same requests:

  • fromPost('param');  
  • fromQuery('param'); 
  • fromRoute('param');
  • fromFiles('param');  

Viewing the params plugin code will demonstrate that it is essentially just a wrapper that references the request object as in the earlier examples. 

Sign Up

NEXT: Create a module in zend 2

This article runs you through the steps of creating a new module in Zend Framework 2.

comments powered by Disqus
Sign Up

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.