The dependency injection container for humans

Overview
layout
home

Downloads per months Total downloads

Average time to resolve an issue Percentage of issues still open

PHP-DI is a dependency injection container meant to be practical, powerful, and framework-agnostic.

Read more on the website: php-di.org

Get community support in the Gitter chat room: Gitter chat

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of php-di/php-di and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Comments
  • Error compiling factory definitions since 6.0.7

    Error compiling factory definitions since 6.0.7

    <?php
    
    declare(strict_types=1);
    
    use function DI\autowire;
    
    use DI\ContainerBuilder;
    use function DI\factory;
    
    require_once __DIR__.'/../vendor/autoload.php';
    
    class Fu
    {
        public function create(): self
        {
            return new static();
        }
    }
    
    class Bar
    {
        public function create(): self
        {
            return new static();
        }
    }
    
    class FuBar
    {
        private $fu;
    
        private $bar;
    
        public function __construct(Fu $fu, Bar $bar)
        {
            $this->fu = $fu;
            $this->bar = $bar;
        }
    }
    
    $builder = new ContainerBuilder();
    $builder->enableCompilation(__DIR__);
    
    $builder->addDefinitions([
        FuBar::class => autowire()
            ->constructorParameter('fu', factory([Fu::class, 'create']))
            ->constructorParameter('bar', factory([Bar::class, 'create']))
    ]);
    
    $dic = $builder->build();
    

    In CompiledContainer.php you'll find

        protected function get3b62a97e28ef909b96b42a793be8a616()
        {
            $object = new FuBar($this->get5ffee756f39d463eb2a0c22906c0f2be(), $this->get5ffee756f39d463eb2a0c22906c0f2be());
            return $object;
        }
    

    As you can see the definition for Bar (Method get5ffee756f39d463eb2a0c22906c0f2be) is used for every Parameter in FuBar::__construct.

    I was able to nail the issue down to \DI\Compiler\Compiler::getHashedValue. In this scenario the parameter string $value is <nested definition>Factory for every factory definition used like above.

    In our case this is a crititcal issue, downgrading to 6.0.6 fixed this.

    Relates to #605

    bug 
    opened by l-x 27
  • PHP-DI 6 ideas

    PHP-DI 6 ideas

    Must haves:

    • minimize BC breaks as much as possible (upgrading should be easy!) - when I say "rename" below, I mean we keep the old names to preserve BC but we deprecate them
    • drop support for PHP 5.4 #361
    • solve the object() helper that does too much and is too magic

    What about PHP 5.5?

    Main ideas:

    Support PHP 7 and above only?

    Remove scopes: #409

    Rename a few helpers to actions:

    • factory() -> call()
    • object() -> create()

    This is hopefully clearer on what will actually be done by the container.

    Same for object() methods (though I'm a little less convinced of the gain vs effort to migrate):

    • ->constructor(...) -> ->parameters(...)
    • ->method(...) -> ->call(...)

    object() is too magic (#294 extends autowiring and other definitions). We can split its behavior into:

    • create(): create an object, doesn't extend autowiring or a previous definition
    • autowire(): create an object using autowiring, also allows to set some parameters/method calls
    • extend(): extend the previous definition to override constructor parameters/method calls #279 (it might even be removed altogether)

    It will be much clearer (less surprises is always better), and we'll be able to add support for "explicit autowiring" where you only get autowiring when using autowire() (optional of course), which I think is really good when you don't want too much magic.

    Add a way to set parameters on call() (#362, #239): call(function (...) {...})->parameters(get('abc'), get('def')).

    Other ideas:

    • migrate the cache to PSR-6? #376

    Summary:

    return [
    
        'foo' => get('bar'),
    
        'foo' => env('FOO'),
    
        'foo' => string('{root}/test.txt'),
    
        'foo' => create(MyClass::class),
        MyClass::class => create(),
        MyClass::class => create()
            ->with('param1', get('foo'))
            ->call('setLogger', get(Logger::class)),
        '*Repository' => create('*DoctrineRepository'),
    
        'foo' => autowire(MyClass::class),
        MyClass::class => autowire()
            ->parameters(get('abc')),
        MyClass::class => autowire()
            ->parameter('param1', get('abc')),
        MyClass::class => autowire()
            ->call('setLogger', get(Logger::class)),
    
        'bar' => extend('foo')
            ->parameter('param2', get('def')),
        'bar' => extend()
            ->call('setLogger', get(Logger::class)),
    
        'foo' => call(function () {
            return 'bar';
        }),
        'foo' => call([Factory::class, 'method']),
        'foo' => call([Factory::class, 'method'])
            ->parameters(get('abc')),
        'foo' => call([Factory::class, 'method'])
            ->parameter('param1', get('abc')),
    
        'api' => decorate(function ($previous, $c) {
            return new CachedApi($previous);
        }),
    
        'log.handlers' => [
            get(StreamHandler::class),
            get(EmailHandler::class),
        ],
        'log.handlers' => add([
            get(SyslogHandler::class),
        ]),
    
    ];
    

    Internal changes:

    The configuration array could be turned into an AST and visitors could be applied (to turn it into a proper definition array). Then the resulting processed array of definitions could be cached.

    Autowiring and annotation reader might not be "definition source" anymore (so much trouble from the beginning because of this).

    That should solve problems of definitions nested in others (#297, #343), making caching easier and much more efficient (cache one array instead of each definition separately), maybe open the door for AST extensions, maybe open the door to compiling? It will also allow "validation passes" for dev environment (e.g. #243).

    That config-to-AST part could be written as a separate package. It allows to write any configuration using PHP arrays, it could be useful. For example I needed exactly that for a framework and started a draft of such a thing (https://github.com/stratifyphp/framework/tree/master/src/Config).

    Feedback and ideas are welcome!

    enhancement 
    opened by mnapoli 24
  • Use wildcards in definitions

    Use wildcards in definitions

    Hi, we are currently integrating PHP-DI 4 in one of our project.

    Because its a good practice to have interfaces for our business services we have to define a lot of PHP-DI interface => implementation mappings.

    For exemple (this sample can also be configured using a PHP-DI configuration array) :

        $container -> set('Application\Service\IAuthorAccountService', \DI\object('Application\Service\Impl\AuthorAccountService'));
        $container -> set('Application\Service\IAuthorNbReadingService', \DI\object('Application\Service\Impl\AuthorNbReadingService'));
        $container -> set('Application\Service\IAuthorPublicationService', \DI\object('Application\Service\Impl\AuthorPublicationService'));
        $container -> set('Application\Service\ILastUpdatedService', \DI\object('Application\Service\Impl\LastUpdatedService'));
        $container -> set('Application\Service\IMailService', \DI\object('Application\Service\Impl\MailService'));
        $container -> set('Application\Service\IPublicationNbReadingService', \DI\object('Application\Service\Impl\PublicationNbReadingService'));
        $container -> set('Application\Service\ISubjectNbReadingService', \DI\object('Application\Service\Impl\SubjectNbReadingService'));
    

    This is correctly working but at the end we will have a lot of mappings even if we have only one instance of our business services in the DI container.

    I think a really good improvement for future releases of PHP-DI would be to have an auto-scanning feature to scan classes with the @Injectable annotation. This is exactly what the Spring Framework does.

    For example in Spring we can do the following to automatically scan classes using the @Component annotation and create an instance of each component in the DI container at starting :

         <context:component-scan base-package="application.service.impl" />
    

    For this reason interface mappgins is not necessary in Spring, each time a @Component annotation is found on a class Spring instanciate this class and injects the associated object inside its DI Container. Then when a @Resource annotation is found on a class attribute Spring look inside its DI container to find one object which implements the specified interface. If multiple objects implementing the interface are present inside the container Spring fails or forces you to define the name of the object to inject.

    In PHP-DI it would be great to have something similar, for example :

    $container = $containerBuilder -> buildDevContainer();
    $container -> scanPackage('Application\Service\Impl');
    

    This would prevent developers to define lots of interface => implementation mappings in PHP-DI.

    Any thoughts about this feature ?

    Thanks,

    Baptiste

    enhancement 
    opened by bgaillard 23
  • V3.0

    V3.0

    Version 3.0

    Issues: Issue list

    • Configuration is reworked from scratch with different backends
    • Provided configuration backends:
      • Reflection
      • Annotations: @Inject, @Injectable
      • PHP arrays
    • As a consequence, annotations are not mandatory anymore, all functionalities can be used with or without annotations.
    • Setter injection
    • Constructor injection
    • Scopes: singleton (share the same instance of the class) or prototype (create a new instance each time it is fetched). Defined at class level.
    • Code now follows PSR1 and PSR2 coding styles
    • More tests
    • ...
    version 
    opened by mnapoli 21
  • Propose to add PHP-DI to Zend Expressive documentation

    Propose to add PHP-DI to Zend Expressive documentation

    Hi, I'm beginning to use Zend Expressive and saw a page dedicated to DI Container integration https://zendframework.github.io/zend-expressive/features/container/intro.

    I think it would be great to add PHP-DI here too, perhaps by proposing a description / a page to the guys who maintain Zend.

    integrations 
    opened by bgaillard 19
  • Document limitations when using lazy loaded dependencies that involve variadic functions

    Document limitations when using lazy loaded dependencies that involve variadic functions

    When using lazy loaded dependencies, I encountered some curious behaviour when handing over more parameters to a function than defined in its signature (variadic functions).

    class Service
    {
        /**
         * @param mixed $param1
         * @param mixed $param2
         * @param mixed $paramN Can be used to supply additional parameters
         */
        public function doStuf($param1, $param2){
            echo func_num_args();
        }
    }
    

    Now let's try to use this Service when fetched from the dependency injection container

    $dic->get('Service')->doStuff(1, 2, 3); //Prints '3' when not lazy loaded
    $dic->get('Service')->doStuff(1, 2, 3); //Prints '2' when lazy loaded
    

    I use this approach to inject extra variables when translating messages like: "User X has logged in on Y", where X and Y would be 'additional' parameters.

    This probably has to do with the intermediate proxy classes that are generated. For example from a generated proxy class:

      /**
         * {@inheritDoc}
         */
        public function doStuf($param1, $param2)
        {
            $this->initializer5683c4a86687a054344119 && $this->initializer5683c4a86687a054344119->__invoke($this->valueHolder5683c4a866860700867865, $this, 'fireEventOnOrder', array('param1' => $param1, 'param2' => $param2), $this->initializer5683c4a86687a054344119);
    
            return $this->valueHolder5683c4a866860700867865->fireEventOnOrder($param1, $param2);
        }
    

    When looking at https://github.com/Ocramius/ProxyManager/issues/177, I think this behaviour is expected. Therefore I think it should be mentioned in the documentation as a warning...

    documentation easy-pick 
    opened by holtkamp 19
  • Is it possible to make Proxy Manager a suggest instead of a requirement?

    Is it possible to make Proxy Manager a suggest instead of a requirement?

    Hi @mnapoli,

    During an installation of PHP-DI using composer I noticed that 'ocramius/proxy-manager' is being installed, which brings the dependencies zendframework/zend-code, zendframework/zend-eventmanager, zendframework/zend-stdlib.

    As far as I can see I do not need those dependencies because I am not using the proxy functionality; would it make sense to move the ocramius/proxy-manager to the require-dev or suggests so that it is not added by default?

    support 
    opened by mvriel 19
  • Uninstantiable defaulted constructor parameter injection issue

    Uninstantiable defaulted constructor parameter injection issue

    I keep encountering this issue, so I thought I'd have a crack at a fix. Unfortunately it wasn't as simple as it initially seemed, so this is only a test case to demonstrate the issue.

    A common pattern we use in my workplace is to have defaulted constructor parameters. We also use interfaces for just about everything, so the class may look something like this:

    class Foo implements FooInterface
    {
        public function __construct(BarInterface $bar, BazInterface $baz = null)
        {
            if (null === $baz) {
                $baz = new Baz;
            }
    
            $this->bar = $bar;
            $this->baz = $baz;
        }
    
        // ...
    }
    

    So I would add definitions to our container something like:

    return array(
        'BarInterface' => DI\object('Bar'),
        'FooInterface' => DI\object('Foo'),
    );
    

    Leaving out a definition for BazInterface beacuse we just want to use the default. Now when you request FooInterface from the container:

    $container->get('FooInterface');
    

    You get a nasty exception something like:

    Entry BazInterface cannot be resolved: BazInterface is not instantiable
    

    The expected result is that get() returns an instance of Foo using the default value for $baz.

    This PR includes a rough integration test that currently fails because of the issue mentioned above. It is not intended to be merged as it doesn't follow the style of your other tests, but should be good enough to aid in diagnosing the cause of the issue.

    Thanks!

    bug 
    opened by ezzatron 18
  • A proxy should call Container::get() instead of creating a new instance itself

    A proxy should call Container::get() instead of creating a new instance itself

    Here is an example.

    Class Foo's constructor requires a value that is not available until a method A is called.

    A creates an instance of Foo calls \DI\Container::set to register this instance. Later in the method A, Foo->method(...) is called in directly.

    If I make Foo lazy loaded, I still get an exception that Foo can't be instantiated because it is missing a dependency that can't be resolved.

    However if I make the classes that depend on Foo lazy loaded, it works. It appears that the proxy will correctly look up Foo in the container in this case.

    It's more intuitive and convenient to me to make Foo lazy loaded in this situation. There may be multiple classes that depend on Foo. Is it possible?

    Did I miss something?

    opened by HappyRay 17
  • Slim integration

    Slim integration

    Hi,

    has anyone done any thinking on integrating php-di with the Slim web framework/thingie?

    This is basically a Slim web app:

    index.php:

    $app = new \Slim\Slim();
    
    $app->get('/orders(/:page)', function ($page = 1) use ($app) {
        $app->render('orders.twig', array( 'page' => $page ));
    });
    

    I could do it hardcoded of course but was wondering if someone came up with something better.

    enhancement integrations 
    opened by bas-i-nl 17
  • Scoped injection per request

    Scoped injection per request

    The container allows values to be overriden in the request context. Values like the response, the current URI, the request itself are overriden in the container if another request comes into place and re-sets these values.

    I'm using PHP-DI with Swoole, which allows this kind of behavior, which is probably the future of PHP so I think scopes like .NET Core are a very valid feature to be implemented. Notice that this Scope implementation would be totally different from the previous and removed version, this time Scopes are finally useful.

    enhancement 
    opened by odahcam 16
  • Why when changing the value of a dependency of an object, the dependency of another object of the same class also changes?

    Why when changing the value of a dependency of an object, the dependency of another object of the same class also changes?

    I created 2 objects of class B. I don't understand why the dependency a of the two objects is the same. When I change the name property of the a dependency of one object, the other object's a dependency also changes. I tried with illuminate/container and it doesn't happen like that "sorry about my english"

    <?php
    
    declare(strict_types=1);
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    use DI\ContainerBuilder;
    
    try {
        $c = (new ContainerBuilder())->build();
    
        // Create 2 objects of class B
        $b1 = $c->make(B::class);
        $b2 = $c->make(B::class);
    
        var_dump(
            $b1 === $b2,       // bool(false)
            $b1->a === $b2->a, // bool(true): Why is the dependency A of 2 objects B is the same?
            $b1->a->name,      // string(7) "default"
            $b2->a->name       // string(7) "default"
        );
    
        $b1->a->name = 'changed';
    
        var_dump(
            $b1 === $b2,       // bool(false)
            $b1->a === $b2->a, // bool(true)
            $b1->a->name,      // string(7) "changed"
            $b2->a->name       // string(7) "changed"
        );
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
    
    class A
    {
        public string $name;
    
        public function __construct(string $name = 'default')
        {
            $this->name = $name;
        }
    }
    
    class B
    {
        public A $a;
    
        public function __construct(A $a)
        {
            $this->a = $a;
        }
    }
    
    
    opened by chaungoclong 1
  • ContainerBuilder.php: use generics for typehints

    ContainerBuilder.php: use generics for typehints

    The type of container that is actually built may be more specialized than the Container base class. As such, make sure we use the proper return typehints.

    I found this issue while testing extensions of the Container class to support a resettable interface, as an alternative solution to #821. This typing issue would arise for anyone trying to extend Container.

    This issue also exists in the v7 branch (with a handful of fairly straightforward conflicts from current master). If you would prefer that I target the v7 branch instead, I'd be happy to make that change.

    opened by hemberger 0
  • PHP 8.1 enum cannot be compiled

    PHP 8.1 enum cannot be compiled

    Hello, I am using PHP-DI in my projects for quite some time and I am currently facing an issue with PHP enums. I am using monolog library for logging in my apps. Recently I have decided to update Monolog from version 2.6.0 to 3.2.0. Enum Monolog\Level was introduced in Monolog version > 3, which is now prefered way of how to set what messages should be logged. In one of my apps I am using container compiling. After Monolog upgrade my app stop working with error

    Fatal error: Uncaught DI\Definition\Exception\InvalidDefinition: Entry "Monolog\Handler\HandlerInterface" cannot be
    compiled: An object was found but objects cannot be compiled
    Full definition:
    Object (
    class = Monolog\Handler\StreamHandler
    lazy = false
    __construct(
    $stream = get(app.log.options.target)
    $level = Monolog\Level::Info
    $bubble = (default value) true
    $filePermission = (default value) NULL
    $useLocking = (default value) false
    )
    setFormatter(
    $formatter = get(Monolog\Formatter\JsonFormatter)
    )
    ) in /var/www/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php:19
    

    I was debugging the issue and end up in Compiler class, where it failed when Monolog\Level should be processed.

    I can get rid of this issue by passing value of enum in my definitions (e.g. use Monolog\Level::Info->value). Is there something, I am missing or this is general issue for all enums? When compiling is off, everything works with enum just fine.

    opened by Ekimik 1
  • Add functionality to reset container entries

    Add functionality to reset container entries

    The purpose of this change is to improve the support for resource management and introspection of the Container class by adding the following methods:

    • Container::reset - unsets an entry in the container

    • Container::initialized - checks if an entry is initialized

    These method names were chosen for consistency with the same features in Symfony's Dependency Injection component.

    The idea here is that if you have an entry in the container that is no longer needed (say, for example, a database connection), then you can remove the entry from the container with reset to free the resource. If it is needed again later, no extra work is needed to get it from the container according to its definition, and a new instance will be constructed.

    The initialized method is related in the sense that there is no existing way to see if an entry is present in the container. It is distinct from the has method, which only reports if an entry can be supplied by the container, not if it has. You may have some logic that depends on if a resource has been allocated yet (i.e. before the first get or after reset).

    Two practical use cases:

    1. A long-running API service has a database connection in its container. After a call to the API completes, the database connection is closed to free up resources and ensure that the connection does not time out. Because the database connection in the container is now invalid, careful measures need to be put in place to ensure that a reconnection to the database is performed before the object in the container is used on the next API call. This essentially removes the "on demand" aspect of the database connection, because the call may not even need a database connection. By using Container::reset, no special reconnection scaffolding is needed; the container will automatically create a new database connection regardless of where or when the next Container::get call is made.

    2. A logging mechanism for the same API service will log certain properties of the database connection after each call. If no database connection has been opened, then no connection should be made to avoid unnecessary resource consumption. Without the introspection provided by Container::initialized, there is no way to determine if a connection has already been opened through the container interface.

    enhancement 
    opened by hemberger 10
  • Unable to composer install with current master branch on PHP 8.1.5

    Unable to composer install with current master branch on PHP 8.1.5

    When attempting to run composer install on latest master branch, I am getting the following message…

    Loading composer repositories with package information
     Updating dependencies
     Your requirements could not be resolved to an installable set of packages.
     
       Problem 1
         - ocramius/proxy-manager[2.11.2, ..., 2.13.1] require php ~7.4.1 || ~8.0.0 -> your php version (8.1.5) does not satisfy that requirement.
         - ocramius/proxy-manager[2.14.0, ..., 2.14.1] require php ~8.0.0 -> your php version (8.1.5) does not satisfy that requirement.
         - Root composer.json requires ocramius/proxy-manager ^2.11.2 -> satisfiable by ocramius/proxy-manager[2.11.2, ..., 2.14.1].
     
     Failed to install packages for  ./composer.json.
    
    opened by opengeek 15
  • Circular definitions

    Circular definitions

    I am using Slim Framework 4 and adding multiple definition files, but getting Circular Errors when I try to decorate() an existing definition from another file.

    /var/www/vendor/php-di/php-di/src/Container.php: line 384 if (isset($this->entriesBeingResolved[$entryName])) { throw new DependencyException("Circular dependency detected while trying to resolve entry '$entryName'"); }

    All the below files returns an array of definitions, and works fine when I remove definitions_b.php or definitions_c.php, meaning it works fine when there are not more than 2 files trying to define and/or alter the same definition.

    $containerBuilder->addDefinitions(['definitions_a.php', 'definitions_b.php', 'definitions_c.php']);
    

    file definitions_a.php

    return [
    'settings' => function () {
           return ['acme' => 123];
               }
    ];
    

    file definitions_b.php

    use function DI\decorate;
    return [
    'settings' => decorate(function ($previous, ContainerInterface $c) {
          $previous['settings]['acme'] = 456;
          $result = Db::getOne('app');
          $previous['settings']['color'] = $result->color;
           return $previous;
        }
    ];`
    

    file definitions_c.php

    use function DI\decorate;
    return [
    'settings' => decorate(function ($previous, ContainerInterface $c) {
           $previous['settings']['acme'] =789;
           return $previous;
        }
    ];
    

    I do understand the non-related problem of order-of-adding, but would please like your advice on the above.

    opened by plasid 5
Releases(6.4.0)
  • 6.4.0(Apr 9, 2022)

    PHP-DI now requires PHP 7.4 or greater.

    • Improve PHP 8.1 support (#791): switch closure serializer for PHP 8.1 support by @shadowhand and @mnapoli in #808 and #811

    Full Changelog: https://github.com/PHP-DI/PHP-DI/compare/6.3.5...6.4.0

    Source code(tar.gz)
    Source code(zip)
  • 6.3.5(Sep 2, 2021)

  • 6.3.4(Jun 10, 2021)

  • 6.3.3(May 1, 2021)

  • 6.3.2(Apr 20, 2021)

  • 6.3.1(Mar 25, 2021)

  • 7.0.0-beta3(Mar 6, 2021)

    Beta release of future PHP-DI 7.0.

    Not ready for production, please test it out.

    • support PHP 8.0 and up
    • #738 support PHP 8 attributes for injections: welcome #[Inject] to replace @Inject!
    • drop support for @Inject used with phpdoc annotations -> only native PHP types are supported now That makes PHP-DI simpler, faster and lighter (no need for the PhpDocReader package)
    • typed everything that can be typed
    • PSR-11 1.2 & 2.0 support
    Source code(tar.gz)
    Source code(zip)
  • 6.3.0(Oct 12, 2020)

    Thanks a lot to the InnoCraft team, the makers of Matomo, for sponsoring this release.

    #727, #737 PHP 8 support

    As well as new releases in dependencies that bring PHP 8 support and these feature to PHP-DI 6:

    #562, https://github.com/PHP-DI/Invoker/pull/30 Support optional parameters before required ones https://github.com/PHP-DI/Invoker/pull/29 Support PHP 7.1 nullable parameters

    Source code(tar.gz)
    Source code(zip)
  • 7.0.0-beta2(Oct 5, 2020)

    Beta release of future PHP-DI 7.0.

    Not ready for production, please test it out.

    • support PHP 7.4 and up (yes, this is important for what's below)
    • #738 support PHP 8 attributes for injections: welcome #[Inject] to replace @Inject!
    • drop support for @Inject used with phpdoc annotations -> only native PHP types are supported now That makes PHP-DI simpler, faster and lighter (no need for the PhpDocReader package)
    • typed everything that can be typed
    Source code(tar.gz)
    Source code(zip)
  • 7.0.0-beta1(Oct 5, 2020)

    Beta release of future PHP-DI 7.0.

    Not ready for production, please test it out.

    • support PHP 7.4 and up (yes, this is important for what's below)
    • #738 support PHP 8 attributes for injections: welcome #[Inject] to replace @Inject!
    • drop support for @Inject used with phpdoc annotations -> only native PHP types are supported now That makes PHP-DI simpler, faster and lighter (no need for the PhpDocReader package)
    • typed everything that can be typed
    Source code(tar.gz)
    Source code(zip)
  • 6.2.4(Oct 1, 2020)

  • 6.2.3(Sep 24, 2020)

  • 6.2.2(Aug 23, 2020)

  • 6.2.1(Jun 18, 2020)

  • 6.2.0(Jun 10, 2020)

    #706 #711 #716 and #717: Support compiling short closures, by using the opis/closure library.

    This also means that we don't require the deprecated jeremeamia/superclosure package anymore.

    Source code(tar.gz)
    Source code(zip)
  • 6.1.0(Apr 6, 2020)

    PHP-DI 6.1 supports PHP 7.2 and up. PHP 7.0 and 7.1 are no longer supported.

    This release also includes:

    • Add autowiring-support for PHP 7.4 typed properties #708 by @bzikarsky
    • Make injectOn use the definition cache #709 by @bzikarsky
    • PHP 7.4 is now fully supported and tested #699 by @jdreesen
    Source code(tar.gz)
    Source code(zip)
  • 6.0.11(Dec 12, 2019)

    #698: Allows namespacing cache keys when using the APCu cache. That makes possible to run multiple applications sharing the same cache (e.g. on the same server) without conflicts.

    Source code(tar.gz)
    Source code(zip)
  • 6.0.10(Oct 21, 2019)

    Another attempt at fixing #605, via #686. This fixes some bugs with platforms like Heroku.

    In previous versions, some random strings were used in the CompiledContainer which caused each regeneration/compilation of the container to have a different result, while no change in the configuration were made. The CompiledContainer has now been made idempotent: "a specific PHP-DI configuration X always results in CompiledContainer Y".

    Source code(tar.gz)
    Source code(zip)
  • 6.0.9(Jul 8, 2019)

    • Fixed #653: Fixes FactoryResolver#resolve ignoring passed parameters
    • Fixed #674 with #675: How to set a closure as value to compiled container
    Source code(tar.gz)
    Source code(zip)
  • 6.0.8(Apr 21, 2019)

  • 6.0.7(Mar 7, 2019)

    #605 Fixes some bugs with platforms like Heroku.

    In previous versions some random strings were used in the CompiledContainer which caused each regeneration/compilation of the container to have a different result, while no change in the configuration were made. The CompiledContainer has now been made idempotent: "a specific PHP-DI configuration X always results in CompiledContainer Y".

    Source code(tar.gz)
    Source code(zip)
  • 6.0.6(Feb 28, 2019)

  • 6.0.5(Sep 17, 2018)

  • 6.0.4(Aug 31, 2018)

  • 6.0.3(Aug 25, 2018)

  • 6.0.2(Apr 23, 2018)

  • 6.0.1(Apr 21, 2018)

  • 6.0.0(Feb 20, 2018)

    This is the complete change log. You can also read the migration guide for upgrading or the blog article to see what's new.

    Improvements:

    • #494 The container can now be compiled for optimum performances in production
    • #294, #349, #449: DI\object() has been replaced by more specific and less ambiguous helpers:
      • DI\create() creates an object, overrides autowiring and previous definitions
      • DI\autowire() autowires an object and allows to override specific constructor and method parameters
    • The container can now be built without parameters: new Container()
    • Definitions can be nested:
      • #490 Definitions can be nested in arrays (by @yuloh)
      • #501 & #540 Autowire definitions can be nested in other definitions
      • #487 & #540 Closures are now handled as factories when they are nested in other definitions
    • #487 Closures in the config are now always interpreted as factories, even when nested inside other definitions
    • #242 Error in case a definition is not indexed by a string
    • #505 Debug container entries
    • #564 Caching was made almost entirely obsolete by the container compilation, however there is still a caching system entirely rebuilt over APCu for covering the last cases that compilation could not address (see php-di.org/doc/performances.html)

    Fixes:

    • #499 & #488 Standardize resolution of nested definitions everywhere. In PHP-DI 5, definitions could be nested in some places (e.g. use a get() in an object definition, etc.). However it did not behave everywhere the same, for example it didn't work for sub-definitions in arrays. Now in PHP-DI 6 all nested definitions will all be recognized and resolved correctly everywhere. Since #494 (compiled container) performance will not be affected so we can implement a more robust behavior.
    • #343 Autowiring and Annotations do not work for object() inside arrays: it now works with the new create() and autowire() helpers

    BC breaks:

    • PHP 7 or greater is required and HHVM is no longer supported
    • DI\object() has been removed, use DI\create() or DI\autowire() instead
    • #409: Scopes are removed, read more in the scopes documentation.
    • Caching was replaced by compiling the container: ContainerBuilder::setDefinitionCache() was removed, use ContainerBuilder::enableCompilation() instead.
    • #463 & #485: Container-interop support was removed, PSR-11 is used instead (by @juliangut)
    • The deprecated DI\link() helper was removed, used DI\get() instead
    • #484 The deprecated \DI\Debug class has been removed. Definitions can be cast to string directly
    • The exception DI\Definition\Exception\DefinitionException was renamed to DI\Definition\Exception\InvalidDefinition
    • The exception DI\Definition\Exception\AnnotationException was renamed to DI\Definition\Exception\InvalidAnnotation
    • #516 DI\InvokerInterface was removed in favor of Invoker\InvokerInterface.

    Be also aware that internal classes or interfaces may have changed.

    Source code(tar.gz)
    Source code(zip)
  • 6.0.0-beta3(Jan 20, 2018)

    3rd beta release for PHP-DI 6.0. Please test it and report if you see any problem (bug or performance regression).

    Migration guide

    Changes since last beta release

    • #567 Ignore errors for invalid referenced definitions during compilation.

    ☝️ This is just a quick summary, all of these changes are listed in the full changelog below with probably more information.

    6.0 changelog

    Improvements:

    • #494 The container can now be compiled for optimum performances in production
    • #294, #349, #449: DI\object() has been replaced by more specific and less ambiguous helpers:
      • DI\create() creates an object, overrides autowiring and previous definitions
      • DI\autowire() autowires an object and allows to override specific constructor and method parameters
    • The container can now be built without parameters: new Container()
    • Definitions can be nested:
      • #490 Definitions can be nested in arrays (by @yuloh)
      • #501 & #540 Autowire definitions can be nested in other definitions
      • #487 & #540 Closures are now handled as factories when they are nested in other definitions
    • #242 Error in case a definition is not indexed by a string
    • #505 Debug container entries
    • #564 Caching was made almost entirely obsolete by the container compilation, however there is still a caching system entirely rebuilt over APCu for covering the last cases that compilation could not address (see php-di.org/doc/performances.html)

    Fixes:

    • #499 & #488 Standardize resolution of nested definitions everywhere. In PHP-DI 5, definitions could be nested in some places (e.g. use a get() in an object definition, etc.). However it did not behave everywhere the same, for example it didn't work for sub-definitions in arrays. Now in PHP-DI 6 all nested definitions will all be recognized and resolved correctly everywhere. Since #494 (compiled container) performance will not be affected so we can implement a more robust behavior.
    • #343 Autowiring and Annotations do not work for object() inside arrays: it now works with the new create() and autowire() helpers

    BC breaks:

    • PHP 7 or greater is required and HHVM is no longer supported
    • DI\object() has been removed, use DI\create() or DI\autowire() instead
    • #409: Scopes are removed, read more in the scopes documentation.
    • Caching was replaced by compiling the container: ContainerBuilder::setDefinitionCache() was removed, use ContainerBuilder::enableCompilation() instead.
    • #463 & #485: Container-interop support was removed, PSR-11 is used instead (by @juliangut)
    • The deprecated DI\link() helper was removed, used DI\get() instead
    • #484 The deprecated \DI\Debug class has been removed. Definitions can be cast to string directly
    • The exception DI\Definition\Exception\DefinitionException was renamed to DI\Definition\Exception\InvalidDefinition
    • The exception DI\Definition\Exception\AnnotationException was renamed to DI\Definition\Exception\InvalidAnnotation
    • #516 DI\InvokerInterface was removed in favor of Invoker\InvokerInterface.

    Be also aware that internal classes or interfaces may have changed.

    Source code(tar.gz)
    Source code(zip)
  • 6.0.0-beta2(Jan 14, 2018)

    2nd beta release for PHP-DI 6.0. Please test it and report if you see any problem (bug or performance regression).

    Migration guide

    Changes since last beta release

    • #564 A caching system was restored, based on APCu
    • #565 Compile more entries

    ☝️ This is just a quick summary, all of these changes are listed in the full changelog below with probably more information.

    6.0 changelog

    Improvements:

    • #494 The container can now be compiled for optimum performances in production
    • #294, #349, #449: DI\object() has been replaced by more specific and less ambiguous helpers:
      • DI\create() creates an object, overrides autowiring and previous definitions
      • DI\autowire() autowires an object and allows to override specific constructor and method parameters
    • The container can now be built without parameters: new Container()
    • Definitions can be nested:
      • #490 Definitions can be nested in arrays (by @yuloh)
      • #501 & #540 Autowire definitions can be nested in other definitions
      • #487 & #540 Closures are now handled as factories when they are nested in other definitions
    • #242 Error in case a definition is not indexed by a string
    • #505 Debug container entries
    • #564 Caching was made almost entirely obsolete by the container compilation, however there is still a caching system entirely rebuilt over APCu for covering the last cases that compilation could not address (see php-di.org/doc/performances.html)

    Fixes:

    • #499 & #488 Standardize resolution of nested definitions everywhere. In PHP-DI 5, definitions could be nested in some places (e.g. use a get() in an object definition, etc.). However it did not behave everywhere the same, for example it didn't work for sub-definitions in arrays. Now in PHP-DI 6 all nested definitions will all be recognized and resolved correctly everywhere. Since #494 (compiled container) performance will not be affected so we can implement a more robust behavior.
    • #343 Autowiring and Annotations do not work for object() inside arrays: it now works with the new create() and autowire() helpers

    BC breaks:

    • PHP 7 or greater is required and HHVM is no longer supported
    • DI\object() has been removed, use DI\create() or DI\autowire() instead
    • #409: Scopes are removed, read more in the scopes documentation.
    • Caching was replaced by compiling the container: ContainerBuilder::setDefinitionCache() was removed, use ContainerBuilder::enableCompilation() instead.
    • #463 & #485: Container-interop support was removed, PSR-11 is used instead (by @juliangut)
    • The deprecated DI\link() helper was removed, used DI\get() instead
    • #484 The deprecated \DI\Debug class has been removed. Definitions can be cast to string directly
    • The exception DI\Definition\Exception\DefinitionException was renamed to DI\Definition\Exception\InvalidDefinition
    • The exception DI\Definition\Exception\AnnotationException was renamed to DI\Definition\Exception\InvalidAnnotation
    • #516 DI\InvokerInterface was removed in favor of Invoker\InvokerInterface.

    Be also aware that internal classes or interfaces may have changed.

    Source code(tar.gz)
    Source code(zip)
Small but powerful dependency injection container

Container (Dependency Injection) This package is compliant with PSR-1, PSR-2, PSR-4 and PSR-11. If you notice compliance oversights, please send a pat

The League of Extraordinary Packages 779 Dec 30, 2022
💎 Flexible, compiled and full-featured Dependency Injection Container with perfectly usable autowiring and support for all new PHP 7 features.

Nette Dependency Injection (DI) Introduction Purpose of the Dependecy Injection (DI) is to free classes from the responsibility for obtaining objects

Nette Foundation 781 Dec 15, 2022
PSR-11 compatible Dependency Injection Container for PHP.

bitexpert/disco This package provides a PSR-11 compatible, annotation-based dependency injection container. Have a look at the disco-demos project to

bitExpert AG 137 Sep 29, 2022
🚀 PHP Service Container with fast and cachable dependency injection.

ClanCats Container A PHP Service Container featuring a simple meta-language with fast and compilable dependency injection. Requires PHP >= 7.0 Pros: M

ClanCats 28 Apr 13, 2022
Twittee is the smallest, and still useful, Dependency Injection Container in PHP

What is Twittee? Twittee is the smallest, and still useful, Dependency Injection Container in PHP; it is also probably one of the first public softwar

null 133 Dec 5, 2022
Dependency Injection System

Aura.Di A serializable dependency injection container with constructor and setter injection, interface and trait awareness, configuration inheritance,

Aura for PHP 342 Dec 1, 2022
Yii Dependency Injection PSR-11 compatible

Yii Dependency Injection PSR-11 compatible dependency injection container that is able to instantiate and configure classes resolving dependencies. Fe

Yii Software 161 Nov 10, 2022
IoC Dependency Injector

auryn auryn is a recursive dependency injector. Use auryn to bootstrap and wire together S.O.L.I.D., object-oriented PHP applications. How It Works Am

Daniel Lowrey 725 Nov 23, 2022
IoC Dependency Injector

auryn auryn is a recursive dependency injector. Use auryn to bootstrap and wire together S.O.L.I.D., object-oriented PHP applications. How It Works Am

Daniel Lowrey 710 Apr 15, 2021
Dependency Manager for PHP

Composer - Dependency Management for PHP Composer helps you declare, manage, and install dependencies of PHP projects. See https://getcomposer.org/ fo

Composer 27.2k Dec 31, 2022
DI Container (PSR-11)

My DI Container It's my own implementation PSR-11 Container Interface. Installation composer require scruwi/container Init $container = new Container(

null 4 Mar 15, 2022
This repository holds all interfaces related to PSR-11 (Container Interface).

Container interface This repository holds all interfaces related to PSR-11 (Container Interface). Note that this is not a Container implementation of

PHP-FIG 9.6k Jan 4, 2023
Extensible DI container for Symfony2

This package contains an implementation of the Symfony 2 DI container that can be extended using other DI containers (from other frameworks).

TheCodingMachine 1 Apr 2, 2014
A small PHP dependency injection container

Pimple Caution! Pimple is now closed for changes. No new features will be added and no cosmetic changes will be accepted either. The only accepted cha

Silex 2.6k Dec 29, 2022
Small but powerful dependency injection container

Container (Dependency Injection) This package is compliant with PSR-1, PSR-2, PSR-4 and PSR-11. If you notice compliance oversights, please send a pat

The League of Extraordinary Packages 779 Dec 30, 2022
💎 Flexible, compiled and full-featured Dependency Injection Container with perfectly usable autowiring and support for all new PHP 7 features.

Nette Dependency Injection (DI) Introduction Purpose of the Dependecy Injection (DI) is to free classes from the responsibility for obtaining objects

Nette Foundation 781 Dec 15, 2022
PSR-11 compatible Dependency Injection Container for PHP.

bitexpert/disco This package provides a PSR-11 compatible, annotation-based dependency injection container. Have a look at the disco-demos project to

bitExpert AG 137 Sep 29, 2022
🚀 PHP Service Container with fast and cachable dependency injection.

ClanCats Container A PHP Service Container featuring a simple meta-language with fast and compilable dependency injection. Requires PHP >= 7.0 Pros: M

ClanCats 28 Apr 13, 2022
Twittee is the smallest, and still useful, Dependency Injection Container in PHP

What is Twittee? Twittee is the smallest, and still useful, Dependency Injection Container in PHP; it is also probably one of the first public softwar

null 133 Dec 5, 2022
Dependency Injection System

Aura.Di A serializable dependency injection container with constructor and setter injection, interface and trait awareness, configuration inheritance,

Aura for PHP 342 Dec 1, 2022