0

I'm rebuilding my current code and I'm trying to do it with dependency injection. I've downloaded Pimple and in one file, I'm trying to create a few examples for myself. In the documentation I came to method extend, but I'm not able to make it work. For test I have created simple class:

class ExtendClass
{
  private $extend = 'false';
    
  public function extendIt()
  {
    $this->extend = 'true';
  }
}

I've created simple object, $DI is instance of Pimple\Container:

$DI['extend'] = function( $c )
{
    return new ExtendClass();
};

I've tried to extend it with this:

$DI->extend( 'extend', function( $extend, $c )
{
    $extend->extendIt();
    return $extend;
} );

But it gave me this error:

Uncaught exception 'InvalidArgumentException' with message 'Identifier "extend" does not contain an object definition.

So i looked to the container nad found out, that I need to add method __invoke into my class, so i added it and make this method to return instance:

class ExtendClass
{
    private $extend = 'false';

    public function __invoke()
    {
        return $this;
    }
    
    public function extendIt()
    {
        $this->extend = 'true';
    }
}

but after that I get this error:

RuntimeException: Cannot override frozen service "extend".

Can someone explain me what I am doing wrong? Thanks.

rsbarro
  • 27,021
  • 9
  • 71
  • 75
M.Svrcek
  • 5,485
  • 4
  • 25
  • 33
  • Are you running $DI->extend( 'extend', function( $extend, $c ) in the setUp method of PHPUnit? – Ali Mar 07 '15 at 15:09

1 Answers1

0

You need to extends service like this:

$DI->extend( 'extend', function($app)
{
    $app['extend']->extendIt();
    return $app['extend'];
} );
desarrolla2
  • 233
  • 2
  • 11