Getting URL Parameters in ZF2 Controllers

Accessing URL parameters from controllers in Zend Framework 2 is extremely easy thanks to the params controller plugin. This plugin exposes various methods that one can use to retrieve parameters from various sources of a request, including from the URL.

I will give examples of the various sources below.

Getting URL Parameters

To get URL parameters within Zend Framework 2 controllers, simply invoke the fromRoute or fromQuery methods on the params controller plugin. The fromRoute method should be used when you wish to retrieve a segment from a segment route for instance, while the fromQuery is used to fetch query parameters from the URL.

The above will fetch the value of a postId parameter if one is available within any of the request sources.

Specifying a Default Value

When fetching parameters, one can also specify a default value that should be returned if the parameter is not available. This could for instance be useful when paginating a set of items; if no page parameter is available, it should default to one. This avoids having to make conditional checks and keeps the code slightly more clean.

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!