Search code examples
phpslimpimple

Modifying Pimple/Slim container


I would like to be able to modify an array on a Pimple container, however, because the services are frozen by Pimple this seems to be impossible.

I have tried the extend() method on the container, however, due to my array not being an object I am unable to modify it.

$container = new Slim\Container();
$container['config'] = ['foo'=>'bar'];
// .... do some other stuff.
$container['config']['baz'] = 'Harry'; // throws an error regarding indirect modification

Using extend

$container = new Slim\Container();
$container['config'] = ['foo'=>'bar'];
$container->extend('config',function($config,$container){
    $config['baz'] = 'Harry';
    return $config;
});
// throws an error PHP Fatal error:  Uncaught InvalidArgumentException: Identifier "config" does not contain an object definition.

Is there no way to modify a definition inside Pimple container? Currently I am passing around a $config array by reference prior to instantiating the container which is less than ideal!

Thanks in advance


Solution

  • Sorry, it turns out that I can just wrap the $config in a function to achieve desired results.

    $container = new Slim\Container();
    $config = ['foo'=>'bar'];
    $container['config'] = function($container) use($config){
        return $config;
    };
    $container->extend('config',function($config,$container) {
        $config['baz']='Harry';
        return $config;
    });
    print_r($container['config']);
    // foo=>bar, baz=>Harry