Using a single controller in Zend Framework

Are you using Zend? Do you have only a core controller and don’t need extraneous URL parameters? Try this.

Most of the time, I am using Zend Framework to its (mostly) full capacity. Models, Controllers, View Helpers – the whole box-and-dice. However, there has been several occasions where I’ve only needed a single controller serving up mostly static pages, or pages leveraging an external service.

The biggest problem that arises in this case when using the default Zend Router, is that action names are treated as controller names. I don’t know about you, but I personally hate seeing when what I actually want to see is

Here’s a nice way to completely tidy up all your actions, serving them from a single controller. (I use a Bootstrap file to initialise my application):

This basically says that my first parameter is always going to be an action name, and everything else is to be parsed as normal. I set request defaults in the array. In this case, the default controller is “index”. This allows everything to be passed straight through to my IndexController.

Addtionally, if you are using modules and want to retain routing for these also (for example, a one-controller site with an admin module), you can add this route rule to your system:

This says that anything starting with “admin” needs to be routed to the admin module, and the rest of the URL is to be parsed as normal.

That’s it! This will allow you to route all requests to a single controller for the front-end, and still maintain a complete module for the administration on the back-end.

Hopefully this cleared up some things for others, as I found the Zend Framework documentation to be quite dismal.

Return JSON data with Zend Framework

Getting Zend to return JSON data can be tricky at times. The JSON helper likes to send the ‘official’ JSON header (application/json), and most browsers are treating that as a download link, resulting in no data to the client and an unfortunate download box.

To bypass this default behaviour, you’ll need to tell the controller how to serve your JSON data:

The key part of this stub is the exit; line. It prevents the view renderer from sending anything, keeping your JSON data intact. Note: json_encode and json_decode only works from PHP version 5.2.1

To output all of your view’s variables in this way, replace $some_var; with:

Hopefully this saved someone a headache or two when dealing with Zend’s puzzling JSON implementation.