v_i_m
v_i_m

Reputation: 171

Optional ZF2 module in application.config.php. Is there a better way?

I need to optionally include some modules in my ZF2 app. The modules are entirely independent with any loaded modules.

In application.config.php, in the config array I can just include the main modules, and then, at the end, based on some conditions, to add the optional module. Like this:

$config = array(
    'modules' => array(
        'Application',
    ),
    ...
);

if (condition) {
    $config['modules'][] = 'OptionalModule';
}

return $config;

Though this works and fixes the problem, I was wondering if there is another way of doing this.

Is it a good approach for this use case? Would there be a nicer way to accomplish this?

Thanks!

Upvotes: 2

Views: 136

Answers (1)

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

I usually do this by using any of the below two methods:

Conditionally load module with local application config

application.config.php:

<?php
use Zend\Stdlib\ArrayUtils;

$config = [
    // You config
];

$local = __DIR__ . '/application.config.local.php';
if (is_readable($local)) {
    $config = ArrayUtils::merge($config, require($local));
}

return $config;

application.config.local.php:

<?php

return [
    // Your config
];

This enables you to have a base application config and load an additional config per deployment. So no if $condition, this is determined by your deployment process, which is most times easier to manage.

Note this also works for deployment configs: application.config.development.php vs application.config.production.php. This is just whatever you like, to suit your needs.

Conditionally execute code in module config

In your Module.php

<?php

namespace MyModule;

use Zend\Mvc\MvcEvent;

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

        $config = $sm->get('Config');
        if ($config['mymodule']['enabled'] === true) {
            // condition
        }
    }
}

Then you can have your module.config.php in your own module folder:

<?php

return [
    'mymodule' => [
        'enabled' => true,
    ],
];

But if youn need to disable this in a certain environment, you add this to your config/autoload/local.php:

<?php

return [
    'mymodule' => [
        'enabled' => false,
    ],
];

Upvotes: 1

Related Questions