Archive for the ‘Zend Framework’ Category

Zend Framework 2 – modules with sub namespaces

Tuesday, November 25th, 2014

The problem – readability

Let us imagine you have a neat organization called “My Organization”, for example. This organization produces software modules, and at one point in time you have decided to adopt Zend Framework 2 module structure. According to ZF2 module naming guidelines you should name your modules as “MyOrgMyModule”, presuming “My Organisation” name is shortened into “MyOrg”. Consequentially namespace is called like this: “MyOrgMyModule\MyClass”.

To enable this module in your ZF2 application, you have to enable it in your application config file (named ./config/application.config.php by ZF2 convention):

Soon someone is bound to notice that namespace operator (“\”) would provide better readability of said modules, and as PHP supports unlimited sub namespaces (unlimited for purpose of this discussion), it would be far better to use that than to just cram UCfirst words one after another. Like this:

The snag

The snag is – your module directories (./module, ./vendor) must follow the exact naming pattern as module names/namespaces. Therefore:
– module name MyOrg\Subset1\Module2 (with the same namespace)
– becomes directory ./module/MyOrg/Subset1/Module2.

But, if you publish your modules, for example on Github, there is no way to clone into subdirectory by default. Also, you usually name Github projects more expressively, for example: php-zf2-module-MyModule1.

The clone command:

will clone into ./php-zf2-module-MyModule1 directory.

Workaround #1 – adjusted directory structure

The obvious answer is: clone into appropriate subdirectory, like this:

This is a fine approach. The only downside is that visual similarity between directory name and Github project name is lost (it is still available in ./vendor/MyOrg/MyModule1/.git/config file though).

Workaround #2 – explicit module path configuration

Then, configure per-ZF2-module paths in you ./config/application.config.php:

Workaround #2 – alternative, more verbose directory structure

For even greater readability, you should clone your modules into vendor-named subdirectories, like this:

Then configure per-ZF2-module paths in you ./config/application.config.php: