Robert Basic's blog

Grouping Zend Framework controllers in subdirectories

by Robert Basic on April 16th, 2011

Thanks to a discussion on the Zend Framework mailing list I learned about a new feature, a feature that allows for grouping action controllers in subdirectories! Well, this is more of an unknown and undocumented feature than new, as it is the part of the framework for at least 3 years.

Subdirectories example

Subdirectories example

Why am I so hyped about this? Because it allows for better code organisation on larger projects. Heck, it might be useful on smaller ones too. For example, if a module Foo has both a backend and a frontend, what I was doing so far was to have the file and class names prefixed with an Admin prefix for the backend files and no prefix for the frontend files, so I can actually see what file belongs where. This can go out of control quite easily.

On the other hand, with this grouping of controllers I can make an Admin directory and just place all the backend related controllers there. Easy, clean and much more easier to see what's where. In my opinion at least :)

Example

Best part is that this feature requires no additional configuration. Create a subdirectory under the controllers directory and place the controller file under that subdirectory. In that pretty screenshot image you can see a FooController.php in the directory called Sub; the class name in that example is Sub_FooController and is accessible via the sub_foo/controller URI. The corresponding view files should be placed in views/scripts/sub/foo/ directory.

A few notes on this:

  • the subdirectory separator in the URI is the underscore and not the slash.
  • The subdirectory name is uppercase: Subdirectory, not subdirectory. In the URI it's lowercase.
  • The view directories for these subdirectories are lowercased, and not uppercase.

The uppercase subdirectory sounds weird, but meh. If needed, the underscore can be "changed" to the slash with a route.

I think the level of possible subdirectories is not limited, but I really can't see an use-case for more than one subdirectory.

Happy hackin'!

Tags: controllers, zend framework.
Categories: Development, Programming.