Welcome to Abdul Malik Ikhsan's Blog

Using ZF Component’s ConfigProvider in Expressive

Posted in Tutorial PHP, Zend Framework by samsonasik on May 24, 2016

If you already tried building Expressive application using modular approach with Expressive Config Manager, you can just use ZF Component’s services by consuming its config provider. If you didn’t use it, you need to first require the Expressive Config Manager in your Expressive application:

composer require mtymek/expressive-config-manager

When done, you can modify the config/config.php like the following:

use Zend\Expressive\ConfigManager\ConfigManager;
use Zend\Expressive\ConfigManager\PhpFileProvider;

$configManager = new ConfigManager([
    new PhpFileProvider('config/autoload/{{,*.}global,{,*.}local}.php'),
]);

return new ArrayObject($configManager->getMergedConfig());

Now, for example, you want to consume Zend\Db services, you can do:

1. Require it

 composer require zendframework/zend-db

2. Register in config/config.php

use Zend\Expressive\ConfigManager\ConfigManager;
use Zend\Expressive\ConfigManager\PhpFileProvider;

$configManager = new ConfigManager([
    new PhpFileProvider('config/autoload/{{,*.}global,{,*.}local}.php'),
    new Zend\Db\ConfigProvider()
]);

return new ArrayObject($configManager->getMergedConfig());

By provide Zend\Db Config Provider, you can now consume its service, let’s try define sample DB config:

// config/autoload/db.local.php
return [
    'db' => [
        'username' => 'root',
        'password' => '',

        'driver' => 'Pdo',
        'dsn' => 'mysql:dbname=test;host=localhost',
        'driver_options' => [
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ],
    ],
];

And now, you can consume \Zend\Db\Adapter\AdapterInterface::class as service. Check the per-component’s ConfigProvider::getDependencyConfig() for available services if you want to use them.

Done 😉