Modifying Pimple/Slim container

940 views Asked by At

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

2

There are 2 answers

0
James Kipling On BEST ANSWER

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
2
geggleto On

You can do this by unsetting the container value first.

Pimple freezes values but will allow you to remove them.

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