Dependency Injection System

Overview

Aura.Di

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

Installation and Autoloading

This package is installable and PSR-4 autoloadable via Composer as aura/di:

composer require aura/di

Alternatively, download a release, or clone this repository, then map the Aura\Di\ namespace to the package src/ directory.

Dependencies

This package requires PHP 7.2 or later. We recommend using the latest available version of PHP as a matter of principle. If you are interested in using this package for older PHP versions, use version 3.x for PHP 5.5+.

Aura library packages may sometimes depend on external interfaces, but never on external implementations. This allows compliance with community standards without compromising flexibility. For specifics, please examine the package composer.json file.

Quality

Scrutinizer Code Quality Code Coverage Build Status

To run the unit tests at the command line, issue composer install and then phpunit at the package root. This requires Composer to be available as composer, and PHPUnit to be available as phpunit.

This package attempts to comply with PSR-1, PSR-2, PSR-4 and PSR-11. If you notice compliance oversights, please send a patch via pull request.

Community

To ask questions, provide feedback, or otherwise communicate with other Aura users, please join our Google Group.

Documentation

This package is fully documented here.

Aura.Di 2.x and 3.x users may wish to read the migrating documentation.

Comments
  • [v3] No auto-resolution with $container->get?

    [v3] No auto-resolution with $container->get?

    All this time I've been assuming that I would be able to do something like $container->get('My\Controller') and it would "just work". Testing it now, and I get a ServiceNotFound exception. :disappointed:

    Why isn't this part supported?

    Featured-request v3 
    opened by glen-84 52
  • Using a service no longer works

    Using a service no longer works

    The issue seem to stem from https://github.com/auraphp/Aura.Di/blob/3.0.0-beta2/src/Container.php#L504, now that the Container is locked after the first instance is created, this makes it not possible to use services.

    The code on http://auraphp.com/packages/Aura.Di/services.html no longer works because at the point of set https://github.com/auraphp/Aura.Di/blob/3.0.0-beta2/src/Container.php#L229 the lock is checked and it would be true hence throwing an Exception.

    v3 
    opened by silentworks 30
  • [v3] Container#call(callable $callable, array $params)

    [v3] Container#call(callable $callable, array $params)

    Edit: See this comment for an update.

    I'm thinking about writing a controller dispatcher that invokes a method on the controller class and injects dependencies as required (route parameters would also be passed in).

    For this, a non-lazy lazyGetCall would probably work (though I haven't yet tested the current lazy option). There's not really any reason for this to be lazy – would you consider adding a non-lazy alternative?

    Question 
    opened by glen-84 28
  • Feature: explicit resolution only setting

    Feature: explicit resolution only setting

    In our project so far we've had a load of bugs that were caused by auto-resolution of the DI. These are generally hard to detect bugs like mysterious class instances that get the wrong constructor parameters even though the code looks fine.

    For example: Changing the name of a parameter in the constructor, but not in the config.

    This causes the class to be auto-resolved and the entry in your config will be ignored completely. It looks at first glance that you declared the parameter, but in reality it is auto-resolved.

    My preference would be that this throws two exceptions. One that the required parameter is not explicitly defined. And one for an unused entry in your config.

    Hence I would like to disable auto-resolving completely and force the use of explicit definitions only.

    opened by Beanow 27
  • Add auto-resolution capability

    Add auto-resolution capability

    This allows type hinted constructor params, that do not have explicit DI values, to receive new instances of their type hinted classes. It also allows explicit auto-resolution of type hints to a specific class or service. Incidentally, params type hinted to array will receive empty arrays when no explicit value is passed.

    opened by pmjones 18
  • Feature request: providers

    Feature request: providers

    At this moment, I am missing an abstraction in Aura.Di. That is the ability to provide an object with features coming from another service. Mostly those objects are collections, for example to provide a list of commands to a console application. This problem is mainly caused due to the fact that we have more than one location that is able to modify the container content (plugins).

    My current solution looks as follows:

    // primary container constructor
    $container->set('console.commands', \new ArrayObject());
    $container->set('console.application', $container->lazy(function () use ($container) {
      $application = new ConsoleApplication();
      foreach ($container->get('console.commands') as $commandName) {
        $application->addCommand($container->get($commandName));
      }
      return $application;
    }));
    
    // in some other container modifier class
    $container->get('console.commands')->append('console.command.my.command');
    $container->set('console.command.my.command', $container->lazyNew(MyCommand::class));
    

    I wish this package could be enhanced with an easier solution. And a solution where I do not need closures, because that prevents the container from being serialized. An example solution looks as follows.

    // primary container constructor
    $container->set('console.commands', \new ArrayObject());
    $container->set('console.application', $container->lazyNew(ConsoleApplication::class));
    
    // in some other container modifier class
    $container->providers[ConsoleApplication::class][] = $container->lazyNew(ConsoleApplicationProvider::class));
    
    // in the provider
    class ConsoleApplicationProvider implements ProviderInterface {
    
       public function provider($container, $object) {
          $object->addCommand($container->newInstance(MyCommand::class));
       }
    
    }
    

    While this has similarities with a factory, it is not completely the same. Hopefully, this can be taken into consideration. When the feedback is positive, I am happy to create a PR for it.

    opened by frederikbosch 16
  • Ability to have more than one argument for setters

    Ability to have more than one argument for setters

    At the moment it is possible to assign just one value to each setter, but it would be nice to have possibility to insert more. In my case I wanted to configure Spot 2 ORM which had a setter with two arguments. I had to override this class and use PHP 5.6 variadic, but there are maybe some other solutions. Of maybe check if version is >= 5.6 use variadic, otherwise use some other trick.

    opened by acim 16
  • some touches

    some touches

    | Q | A | | --- | --- | | Bug Fix? | n | | New Feature? | n | | BC Breaks? | n | | Deprecations? | n | | Tests Pass? | n | | Fixed Tickets | | | License | MIT | | Doc PR | |

    Sent using Gush

    opened by cordoval 16
  • Does Aura.Di have an equiv. to Laravel's

    Does Aura.Di have an equiv. to Laravel's "contextual binding"?

    Laravel's container supports what they call "Contextual Binding" where you can specify different values for constructor parameter resolution on an instance depending on where the instance is being used.

    I recently ran into a need for this when writing some RabbitMQ code. I had a class that handled publishing data to an exchange and I wanted to use 2 instances of this class in different places in my code but in each place I wanted to provide an 'exchange' object instance that was instantiated with a different exchange name string.

    If there is no similar functionality already, I thought a possibly easy to use generic approach would be the ability to set named keys on a specified class, like we do for parameter defining, but which have the extra feature that they 'percolate down' until they are consumed.

    For instance: class A needs an instance of class B and this class B then needs an instance of class C. The constructor for class C has a constructor parameter called exchangeName. You could defined class A as having a key of exchangeName with a value of foo and when an instance of A is created, the instance of class C receives the value of foo on it's constructor for the parameter exchangeName.

    This way, if both class A and class D need instances of class B with different values of exchangeName for class C this is easy to setup.

    opened by far-blue 15
  • Convert class names to fully qualified names

    Convert class names to fully qualified names

    use Aura\Di\Container; use Aura\Di\Forge; use Aura\Di\Config;

    $di = new Container(new Forge(new Config));

    $this->di->setter['Foo\Bar']['setBaz'] = $di->lazyGet('Baz'); $this->di->set('foobar', $this->di->lazyNew('\Foo\Bar'));

    setBaz will not be called upon \Foo\Bar instantiation, because setter was defined as Foo\Bar. Same with constructor params definitions. I think we should convert all class names to fully qualified names internally:

    1. newInstance
    2. param
    3. setter
    4. lazyNew
    opened by MAXakaWIZARD 14
  • Explicit inheritance only

    Explicit inheritance only

    Hi,

    As I said in https://groups.google.com/d/msg/auraphp/OBbGxJvZcho/KSip3TAek4gJ I does not seems normal to inherit of default value of parents.

    My real goal is to add automatic resolution of type hinted arguments, it does not seems normal to inherit of that either. So I changed inheritance of constructor params to explicit params only (params defined in the DI).

    There are also some other small changes before that (fix docblock and use containerInterface in the factory)

    I tried to do atomic commits, so you can pick what you want and see the process i've followed.

    opened by adriengibrat 13
  • Question: What is the return value when invoking lazyNew with args?

    Question: What is the return value when invoking lazyNew with args?

    In 4.x.

    The following test code is correct or not?

    --- a/tests/ContainerTest.php
    +++ b/tests/ContainerTest.php
    @@ -190,6 +190,16 @@ class ContainerTest extends TestCase
             $this->assertSame($items, $instance->getItems());
         }
     
    +    public function testLazyNewInvokable()
    +    {
    +        $lazy = $this->container->lazyNew(
    +            'Aura\Di\Fake\FakeInvokableClass',
    +            ['foo' => 'construct']
    +        );
    +        $invoke = $lazy('invoke');
    +        $this->assertSame('constructinvoke', $invoke);
    +    }
    +
         public function testLockedMagicGet()
         {
             $this->container->lock();
    
    Question 
    opened by kenjis 2
Releases(4.2.1)
  • 4.2.1(Jan 4, 2022)

  • 4.2.0(Jan 4, 2022)

    • (CHG) Upgrade to PHP 7.4+ and PHP 8.0
    • (CHG) Upgrade psr/container to ^2.0
    • (CHG) Upgrade phpunit to ^9.5
    • (CHG) Resolver now checks if class exists before calling get_parent_class
    • (CHG) Wrapped ReflectionClass calls in a try catch
    • (CHG) Removed acclimate/container.
    • (ADD) Replace acclimate/container with CompositeContainer
    Source code(tar.gz)
    Source code(zip)
  • 4.1.0(May 26, 2020)

  • 4.0.0(Jul 17, 2019)

    • (CHG) Upgrade to PHP 7.2+ only, strict types enabled

    • (CHG) Dropped HHVM support

    • (CHG) Signatures of methods in ContainerConfigInterface changed.

    • (CHG) LazyRequire and LazyInclude do not accept another lazy

    • (CHG) Removed container interop dependency

    • (CHG) Removed unsupported community channels

    • (ADD) Contextual parameters

    • (ADD) Producer

    Source code(tar.gz)
    Source code(zip)
  • 4.0.0-beta1(Jul 11, 2019)

    • (CHG) Upgrade to PHP 7.2+ only, strict types enabled

    • (CHG) Dropped HHVM support

    • (CHG) Signatures of methods in ContainerConfigInterface changed.

    • (CHG) LazyRequire and LazyInclude do not accept another lazy

    • (CHG) Removed container interop dependency

    • (CHG) Removed unsupported community channels

    • (ADD) Contextual parameters

    • (ADD) Producer

    Source code(tar.gz)
    Source code(zip)
  • 4.0.0-alpha1(Apr 26, 2019)

    • (CHG) Upgrade to PHP 7.2+ only, strict types enabled

    • (CHG) Dropped HHVM support

    • (CHG) Signatures of methods in ContainerConfigInterface changed.

    • (CHG) LazyRequire and LazyInclude do not accept another lazy

    • (CHG) Removed container interop dependency

    • (CHG) Removed unsupported community channels

    • (ADD) Contextual parameters

    • (ADD) Producer

    Source code(tar.gz)
    Source code(zip)
  • 2.2.5(Dec 24, 2018)

    To remove 7.x warning, replace list() ... each() with foreach.

    Also update the Travis configuration.

    Thanks to @dstepe for these changes!

    Source code(tar.gz)
    Source code(zip)
  • 3.4.0(Jul 30, 2017)

  • 3.3.0(Jul 25, 2017)

    • (DOC) Update documentation. PR #140.

    • (CHG) Rearranging code to achieve full test coverage with the existing test suite. PR #141.

    • (ADD) ResolutionHelper. PR #143. Fixes #133.

    • (Add) ConfigCollection. PR #146.

    • (CHG) Update Reflector.php for PHP 7.2 compatibility. PR #148.

    • (CHG) Travis CI changes. PR #152.

    • (CHG) Removed CHANGES.md. Added CHANGELOG.md

    Source code(tar.gz)
    Source code(zip)
  • 3.2.0(Oct 4, 2016)

    This release adds these new features.

    • (ADD) LazyInclude and LazyRequire can now recieve a LazyValue as a filename, so that the filename is not resolved until the include/require is invoked.
    • (ADD) Allow direct use of lazies in Lazy; cf PR #128.
    • (ADD) Add a new LazyCallable type for injecting callable services; cf. PR #129.
    • (CHG) LazyValue now resolves lazies itself; cf. PR #137.
    • (ADD) Add a new LazyArray type for injecting arrays of lazy-resolved values; cf PR #138.

    There are also various documentation improvements, and the package now provides (via Composer) the virtual package container-interop-implementation.

    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(Mar 23, 2016)

    This release has one documentation addition, and one feature addition.

    • Added documentation for upgrading/migrating from 2.x to 3.x
    • In ContainerBuilder::newConfiguredInstance(), added the ability to pass a ContainerConfig object instance as a config specification.
    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Mar 14, 2016)

  • 2.2.4(Jan 21, 2016)

    • Fixes #91 property-read designation causes PHPStorm to have syntax error. Changed @property-read to @property so they will still be auto-completed by IDE. Thank you David Stockton, Brandon Savage.
    • Fix the doc comments.
    Source code(tar.gz)
    Source code(zip)
  • 3.0.0-beta2(Dec 21, 2015)

    This is the second beta release of this library, and likely the last before a stable release (barring unexpected feature changes and bugfixes).

    • (BRK) Container methods newInstance() and get() now lock the Container automatically. (See note below.)
    • (CHG) $di->params now allows null as a parameter value.
    • (ADD) ContainerConfigInterface
    • (ADD) Better exception messages.
    • (DOC) Add and update documentation.

    Regarding auto-locking of the Container after newInstance() and get():

    This prevents errors from premature unification of params/setters/values/etc. in the Resolver. As a result, do not use Container newInstance() or get() before you are finished calling $params, $setters, $values, set(), or other methods that modify the Container. Use the lazy*() equivalents to avoid auto-locking the Container.

    Source code(tar.gz)
    Source code(zip)
  • 3.0.0-beta1(Jun 3, 2015)

    • BREAK: Rename Aura\Di\_Config\AbstractContinerTest to Aura\Di\AbstractContainerConfigTest.
    • BREAK: The ContainerBuilder no longer accepts pre-built services, only config class names.
    • BREAK: Remove the Aura\Di\Exception\ReflectionFailure exception, throw the native \ReflectionException instead.
    • BREAK: Previously, the AutoResolver would supply an empty array for array typehints, and null for non-typehinted parameters. It no longer does so; it only attempts to auto-resolve class/interface typehints.
    • CHANGE: Add .gitattributes file for export-ignore values.
    • CHANGE: Allow PHP 5.5 as the minimum version.
    • ADD: Allow constructor params to be specified using position number; this is in addition to specifying by $param name. Positional params take precendence over named params, to be consistent pre-existing behavior regarding merged parameters.
    • DOCS: Update documentation, add bookdown files.
    Source code(tar.gz)
    Source code(zip)
  • 2.2.3(May 31, 2015)

  • 3.0.0-alpha1(May 18, 2015)

  • 2.2.2(Mar 26, 2015)

  • 2.2.1(Mar 26, 2015)

    This release restructures the testing and support files, particularly Composer. Note the changes in how tests are run in the new README.md.

    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Mar 16, 2015)

    This release has a couple of feature improvements: traits in ancestor classes and in ancestor traits are now honored, and the DI container can now be serialized and unserialized (unless it contains closures).

    • ADD: The Factory now gets all traits of ancestor classes & ancestor traits.
    • NEW: Class Aura\Di\Reflection decorates ReflectionClass to permit serialization of the DI Container for caching.
    • FIX: The ContainerBuilder now call setAutoResolve() early, rather than late.
    • FIX: If the class being factories has no __construct() method, instantiate without constructor.
    • DOC: Update documentation and support files.
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Nov 6, 2014)

    This release incorporates functionality to optionally disable auto-resolution. By default it remains enabled, but this default may change in a future version.

    • Add Container::setAutoResolve(), Factory::setAutoResolve(), etc. to allow disabling of auto-resolution
    • When auto-resolution is disabled, Factory::newInstance() now throws Exception\MissingParam when a constructor param has not been defined
    • ContainerBuilder::newInstance() now takes a third param to enable/disable auto-resolution
    • AbstractContainerTest now allows you to enable/disable auto-resolve for the tests via a new getAutoResolve() method
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Oct 4, 2014)

    • DOC: In README, note that magic-call setters will not work.
    • BRK: Related to testing under PHP 5.3, remove the ContainerAssertionsTrait. The trait is not 5.3 compatible, so it has to go. Instead, you can extend the Aura\Di_Config\AbstractContainerTest in tests/container/src/ and override the provideGet() and provideNewInstance() methods. Sorry for the hassle.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-beta2(Sep 3, 2014)

    Second beta release.

    • REF: Extract object creation from Container into Factory
    • DOC: Complete README rewrite, update docblocks
    • ADD: The Factory now supports setters from traits.
    • ADD: LazyValue functionality.
    • ADD: Auto-resolution of typehinted constructor parameters, and of array typehints with no default value, along with directed auto-resolution.
    • ADD: ContainerAssertionsTrait so that outehr packages can more easily test their container config classes.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-beta1(Apr 10, 2014)

    Initial 2.0 beta release.

    • Container v1 configurations should still work, with one exception: the lazyCall() method has been removed in favor of just lazy(). Replace lazyCall() with lazy() and all should be well.
    • Now compatible with PHP 5.3.
    • Uses PSR-4 autoloading instead of PSR-0.
    • The package now has a series of Lazy classes to represent different types of lazy behaviors, instead of using anonymous functions.
    • No more cloning of Container objects; that was a holdover from when we had sub-containers very early in v1 and never really used.
    • Removed Forge and placed functionality into Container.
    • Removed the old Config object; $params and $setter are now properties on the Container.
    • No more top-level '*' config element.
    • Renamed Container getServices() to getInstances().
    • Renamed Container getDefs() to getServices().
    • Added ContainerBuilder and new Config object for two-stage configuration.
    • Now honors $setter values on interface configuration; that is, you can configure a setter on an interface, and classes implementing that interface will honor that value unless overridden by a class parent.

    Thanks to HariKT, Damien Patou, Jesse Donat, jvb, and Grummfy for their contributions leading to this release!

    Source code(tar.gz)
    Source code(zip)
Owner
Aura for PHP
High-quality, well-tested, standards-compliant, decoupled libraries that can be used in any codebase.
Aura for PHP
A modern, ultra lightweight and rocket fast Content Management System

Redaxscript A modern, ultra lightweight and rocket fast Content Management System for SQLite, MSSQL, MySQL and PostgreSQL. Installation Clone the repo

redaxscript 247 Nov 12, 2022
A system to help parents call their children inside the school when they are outside

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

null 1 Jan 15, 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
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
The dependency injection container for humans

layout home PHP-DI is a dependency injection container meant to be practical, powerful, and framework-agnostic. Read more on the website: php-di.org G

null 2.4k Jan 4, 2023
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
Provide a module to industrialize API REST call with dependency injection using Guzzle library

Zepgram Rest Technical module to industrialize API REST call with dependency injection using Guzzle library. Provides multiple features to make your l

Benjamin Calef 6 Jun 15, 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
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
Automatic SQL injection and database takeover tool

sqlmap sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of

sqlmapproject 25.7k Jan 5, 2023
Docker environment for practicing pentesting techniques about SQL injection

SQL Injection Playground Docker environment for practicing pentesting techniques about SQL injection.

ommadawn46 23 Aug 2, 2022
FUGIO: Automatic Exploit Generation for PHP Object Injection Vulnerabilities

FUGIO FUGIO is the first automatic exploit generation (AEG) tool for PHP object injection (POI) vulnerabilities. When exploiting a POI vulnerability,

KAIST Web Security and Privacy Lab 53 Dec 23, 2022
Dictionary of attack patterns and primitives for black-box application fault injection and resource discovery.

FuzzDB was created to increase the likelihood of finding application security vulnerabilities through dynamic application security testing. It's the f

FuzzDB Project 7.1k Dec 27, 2022
Application with SQL Injection vulnerability and possible privilege escalation

Application with SQL Injection vulnerability and possible privilege escalation. Free vulnerable app for ethical hacking / penetration testing training.

Filip Karczewski 56 Nov 18, 2022
Dobren Dragojević 6 Jun 11, 2023
Static code analysis to find violations in a dependency graph

PhpDependencyAnalysis PhpDependencyAnalysis is an extendable static code analysis for object-oriented PHP-Projects to generate dependency graphs from

Marco Muths 546 Dec 7, 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