Skip to content

Instantly share code, notes, and snippets.

@mnapoli
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnapoli/d7d001da691a1a806c6e to your computer and use it in GitHub Desktop.
Save mnapoli/d7d001da691a1a806c6e to your computer and use it in GitHub Desktop.
Extending definitions in PHP-DI 5

Extending definitions in PHP-DI 5

Arrays

Extend: definition

  • DI\add()
// Declare an array
return [
    'array' => [
        get(Entry::class),
    ],
];
// Modify an array
return [
    'array' => add([
        get(NewEntry::class),
    ]),
];

Strings

Extend: entry

  • DI\string
return [
    'path.tmp' => '/tmp',
    'log.file' => string('{path.tmp}/app.log'),
];

Factories

Extend: entry

  • DI\factory()
  • DI\decorate()
return [
    // Decorate the same instance
    ProductRepository::class => decorate(function($previous) {
        return new CachedProductRepository($previous);
    }),
];

Decorating another instance is just a normal factory getting a dependency from the container.

Objects

This will not be implemented, but left for documentation

Extend: definition

  • DI\object()
  • DI\extend()
return [
    Foo::class => object(Bar::class)
        ->constructor(...),
];
return [
    // Replace (BC break with PHP-DI 4)
    Foo::class => object(Bim::class)
        ->constructor(...),
    // Extend the previous definition
    Foo::class => extend()
        ->constructorParameter(...),
    // Extend another definition
    Test::class => extend(Foo::class)
        ->constructorParameter(...),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment