Search code examples
phpzend-frameworkmodulenaming

in Zend Framework 2 or 3, can module name be same as class name?


We would like to create a module for our project called Memcached. This way we can have namespaced services (e.g. Memcached\Service\Get) which perform actions using php's installed Memcached class.

However, we notice the following lines in zendframework/zend-modulemanager/src/Listener/ModuleResolverListener.php

if (class_exists($moduleName)) {
    return new $moduleName;
}

This means that if we name our module Memcached, then loading the module simply will not work. The module will be instantiated as a Memcached object rather than the desired Memcached\Module object.

So, is there any way we can simply name our module Memcached? Or, do we need to be more creative and name our module something like MemcachedModule? We would prefer not to do the latter since none of our other modules have this Module suffix.


Solution

  • Zend Framework 3 has been patched so that a module may be named the same as an existing class. The following code was added to the ModuleResolverListener:

    $class = sprintf('%s\Module', $moduleName);
    if (class_exists($class)) {
        return new $class;
    }
    

    So now, for example, we can create our own Zend Module called Memcached\Module which will not conflict with php's built in Memcached class.

    For more info, view the patch on GitHub.