Load different config based on the result of a Service function in Zend Framework 2

78 views Asked by At

Is it possible in ZF2 to load a different config file (or just manually add an array to the existing config) based on a function in a Service (or model)?

To be more precise, I have a (third party) module that needs a bunch of custom settings from the config.

In one of my own modules, in module.config.php I have a custom config setting:

'my_custom_config' => array(
    'display_something' => true,
),

Then in an invokable service I have a function, say isDisplaySomething(), that will determine whether display_something is true or false.

My first try was to call that function in getConfig() of Module.php and then add it to the config as an array, but I can't figure out how to access the Service there.

Then I tried to overwrite Configuration in the onDispatch() in a controller, but I can't access the ServiceManager there (and it's probably not a very elegant solution anyway).

Any ideas how to solve this problem?

1

There are 1 answers

3
Wilt On

For dependencies on a value from config I would suggest you setup a factory to create your service. Something like this:

<?php

namespace My\Factory;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use My\Service\DisplayService;

/**
 * Factory for creating the DisplayService
 */
class DisplayServiceFactory implements FactoryInterface
{
    /**
     * Create the DisplayService
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return DisplayService
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = array();
        if ($serviceLocator->has('config')) {
            $config = $serviceLocator->get('config');
        }

        // Default value in case nothing in config
        // An alternative is to throw an exception if no value found in config.
        $displaySomething = true;

        if(isset($config['my_custom_config'] && isset($config['my_custom_config']['display_something'])){
            $displaySomething = $config['my_custom_config']['display_something'];
        }

        // Use setter to set the value or use constructor dependency.
        $displayService = new DisplayService();
        $displayService->setDisplaySomething($displaySomething);

        return $displayService
    }
}

And then in your module.config.php:

'service_manager' => array(
    'factories' => array(
        'My\Service\DisplayService' => 'My\Factory\DisplayServiceFactory'
    )
)

Now you can get your service from your service manager like this:

$serviceManager->get('My\Service\DisplayService');

and it will have your $displaySomething value.