Sergii
Sergii

Reputation: 3

Global and module config interaction

Let's imagine I have global application configuration

return array(

'languages' => array(
    'allowed'   => array('de', 'en'),
),

);

And I have module configuration with the routes description. I need routes, based on global configuration, so I need to read global application config within the module to compose my routes according to languages->allowed values (constraints for the segment type route)

What is the best way to get global configuration values from the module configuration script? is it correct at all to manipulate data in configuration file instead of simple array return?

Upvotes: 0

Views: 97

Answers (1)

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

You should think a bit more ahead of your problem. You want to create a route structure based on your configuration. The configuration could come from everywhere: module config, local config and global config. It is therefore quite hard to base your module's config on a global one.

What you can do, is create the routes later. For example, you create in your module Foo the config like this:

'routes_foo' => array(
  'bar' => array(
    'type'    => 'segment',
    'options' => array(
      'route' => ':locale/foo/bar',
      'constraints' => array(
        'locale' => '%LOCALE%',
      ),
    ),
  ),
),

And in your module class:

namespace Foo;

class Module
{
    public function onBootstrap($e)
    {
        $app = $e->getApplication();
        $sm  = $app->getServiceManager();

        $config  = $sm->get('config');
        $routes  = $config['routes_foo');
        $locales = $config['languages']['allowed'];

        $routes = $this->replace($routes, array(
            '%LOCALE%' => sprintf('(%s)', implode('|', $locales)
        );

        $router = $sm->get('router');
        $router->routeFromArray($routes);
    }

    public function replace($array, $variables)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$name] = $this->replace($value, $variables);
            }

            if (array_key_exists($value, $variables)) {
                $array[$name] = $variables[$value];
            }
        }

        return $array;
    }
}

What happens is you grab the routes from your config (those are not automatically injected in the router). There you also load all languages from your global config. Then your "custom" routes have (at several places) a "magic" configuration key, which will be replaced by a regex constraint for the locales: (en|de). That parsed config is then injected into the router.

Upvotes: 2

Related Questions