Thoughts on module directory structure – Rob Allen's DevNotes


: 9

I've been working on a Zend Framework 2 module within a larger project that doesn't have that many PHP class files. Specifically, it has a controller, a mapper, an entity, a service and a form.

As a result, the traditional Zend Framework 2 directory structure for the Account module looks like this (with class names in brackets):

That's a lot of directories for not many files!

As a result, I decided to flatten it to this:

This is much more sane for a module with so few classes.

Minimising even more

Interestingly, while ZendLoaderStandardAutoloader is PSR-0 compliant, it also allows for a different top-level directory name for the classes within a single namespace. This would allow for the removal of the Account folder within src too, i.e a structure like this:

This has no extraneous directories at all, but obviously you can only have one namespace within src.

To do this, you simply modify getAutoloaderConfig() within Module.php, so that it looks like this:

Obviously, this is no longer PSR-0 compliant, but does mean that you don't have to worry about that extra directory in src. Also, obviously, you can only have one namespace within src too.

Of course, you can have subdirectories (sub-namespaces) if you wanted to too. e.g. you could organise the files into something like this:

As this is no-longer PSR-0 compliant, it's arguable that it's not a "best practice", however it is very clear and understandable.

Remove src/

Finally, you could even remove the src folder and put the class files directly in the module's root directory:

The autoloader configuration looks like this:

Ironically, this is PSR-0 compliant, even though it's less clear in this situation!

However, if your module consists solely of PHP classes and maybe a config file, then there's no need for a src directory at all.

Take away

So, in summary, the standard ZF2 module directory structure that you see everywhere is just a recommendation. There's no need to follow it slavishly if your needs are better served with a different structure.