zend-frameworkzend-framework2servicemanager

Use Service Manager Zend Framework 2


if I have a service manager in the module Category, such as, can I have read from Category in module Application?

I have done so in Module.php in Application, 'list-category' is located in the module.config.php file of the module Category:

public function onDispatch(MvcEvent $e)
{
    // get service manager from the application object
    $sm = $e->getApplication()->getServiceManager();
    // get categories service
    $categories = $sm->get('list-category');
    // get view model
    $vm = $e->getViewModel();
    // store category list in a variable
    $vm->setVariable('categories', $categories);
}

I have read the service manager by in Module Category in Application.


Solution

  • Yes, you can use a service added to the Service Manager in module A within module B. The services are just added to the service manager within different modules, but are available across modules because the configuration files are merged together by the Module Manager and then handed to the Service Manager. That is why it is a good idea to namespace the service names to avoid naming collisions across modules. Just fetch it like you normally would and it should work.

    In regards to the code that you provided, then what is the problem? Is it not working? Do you get any errors? What is the contents of $categories? Did you attach your function to the Event Manager? If not, then this article shows you how it can be done. Also, please carefully consider if you want to do such an operation on every request for a page within your Category module. I do not know your reasoning, but to do such a thing on every page load, you should have a good reason to do so.