The Zend Framework routing process

by Naneau

Because I noticed some people find it difficult to understand the routing process the Zend Framework uses by default, I decided to write a little explanation. It’s really easy once you get the hang of it, even though it may seem complicated at first.

The Zend Framework is based on the Model View Controller principle. This means that for each request you make (every URL you type into your address bar) there should be a matching controller file and action. In that action you could then use models to create a view.

Now, I’ve put up a little tutorial on how to get started with the framework. In it you create a controllers directory and an IndexController.php file. Afterwards you can browse to your site and see a messaged echoed from that file. How does that work?

If you enter a URL the front controller (that’s the one in your bootstrap file) looks for three things. The first is a controller, the second is an action, and the third is parameters. If you enter a url like: http://yoursite.com/foo/bar/baz/abcdefg this would break down to:

a controller: foo
an action: bar
a parameter: baz with value ‘abcdefg’

It would then try to create an object of the class FooController, for which it would look in a file called FooController.php (in your controllers directory). On that object it would try to call a method barAction(). The parameter baz would be set, having a value of ‘abcdefg’.

If you don’t enter an action name, it would look for an indexAction() method and try to call that. If you don’t specify a controller name it would likewise try to look for an IndexController class in an IndexController.php file. That’s the reason I created an IndexController file with an indexAction in my tutorial on setting up the framework. It’s the default controller and default action.

Now, this is the basic strategy for creating controllers and actions. There are more advanced options, like creating modules and using a __call() method. But you should be able to get started now. The beauty of this approach is that you get URLs for your application that are understandable to both computers and humans.