Download the PHP package suhock/dependency-injection without Composer

On this page you can find all versions of the php package suhock/dependency-injection. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package dependency-injection

Dependency Injection Library for PHP

A compile-and-validate dependency injection container for PHP 8.4+, built for both long-running applications and per-request processes.

Highlights

Table of Contents

Installation

Compatibility

The library requires PHP 8.4 or later and is tested on PHP 8.4 and 8.5.

The only required runtime dependency is the first-party suhock/disposable package; there are no third-party runtime dependencies. Persistent caching of compiled plans is available through OPcache (which ships with PHP) or the optional ext-apcu extension; see Caching compiled plans.

Basic usage

The ContainerBuilder class contains the methods for configuring the container: the add* methods, remove(), and configure(). Its build() method compiles that configuration into an immutable Container, which provides get(), has(), createScope(), and dispose(). Start by constructing a builder.

Next, configure the builder: tell it how it should resolve specific services in your application.

Finally, call build() to compile and validate the whole graph and obtain the container, then call get() on it to retrieve an instance of your application and run it. See Building the container for what build() checks and how a misconfiguration is reported.

The container will inject the constructor's dependencies and provide your application the instance.

If your application has other entry points (e.g., controllers), it might be useful to inject the container into the part of your application that invokes those entry points (e.g., a router). There is nothing to add for this: ContainerInterface auto-binds to the current resolution root, so a router resolved from the container receives the container itself. See Scopes for the full auto-binding rules, including what a router resolved from a scope receives instead.

[!WARNING] Reserve this for dispatchers that only know the required type at runtime. Everywhere else, inject the concrete dependency directly; pulling it from the container (the service locator pattern) makes code harder to test and refactor.

Building the container

ContainerBuilder::build(): Container compiles the configured dependency graph, validates it, and returns an immutable Container. Every service you add must be resolvable. If the configuration has a defect, build() reports it as an error rather than waiting until you request the service.

If validation finds any guaranteed-failure defect, build() throws one Suhock\DependencyInjection\Validation\ContainerValidationException carrying every problem it found, not just the first:

The builder is still usable after a failed build: fix the configuration and call build() again; each successful build() also produces a fully independent Container.

build() reports every one of the following as a build error:

Build performance

Without a cache, build() recompiles and revalidates the whole graph every time it is called. That is inexpensive for most applications, but on a per-request lifecycle such as PHP-FPM you pay that cost on every request. Supplying a CacheInterface (e.g. OpcacheCache or ApcuCache) lets build() store the validated plans under a fingerprint of the configuration; rebuilding an unchanged configuration loads the stored plans and skips compilation and validation entirely:

With a persistent cache, each later build() of an unchanged configuration costs little more than a hash and a cache lookup; the first build after a deploy or a configuration change still pays for full compilation and validation. A worker-mode runtime that builds once at boot (see Caching compiled plans for the available cache backends.

Graph diagnostics

exportDependencyGraph() exports the dependency graph build() would produce as plain data for external tooling: every service (including the auto-bound ones) and every satisfied dependency edge, with the injection point each edge flows through and whether it is required.

The export mirrors what resolution would actually traverse. Unsatisfiable injection points produce no edge (validation reports those); an added-but-never-chosen union member gets no incoming edge; and dependencies hidden inside factory bodies do not appear. exportDependencyGraph() never throws, so a configuration that would fail build() still exports.

Instance lifetime

The lifetime of an instance determines when the container should request a fresh instance of a class. There are three lifetime strategies for classes: singleton, scoped, and transient.

Singleton

Singleton instances are persisted for the lifetime of the container. When the container receives a request for a singleton instance for the first time, it will call the factory that you specified for that class, store the result, and then return it. Any time the container receives a subsequent request for that class, directly or through any scope, it will return that same instance.

Scoped

Scoped instances are persisted for the lifetime of a scope created by Container::createScope(). Each scope receives its own instance the first time it requests the class, and that instance's dependencies are resolved from the scope, so scoped services can depend on other scoped services. Requesting a scoped instance with no scope active (directly from the root container, or from a singleton's dependency graph, which always resolves against the root) throws a ScopeException.

Transient

Transient instances are never persisted and the container provides a fresh value each time an instance is requested. Each time the container receives a request for a transient instance, it will call the factory you specified for that class.

Scopes

A scope represents a bounded unit of work, such as an HTTP request in a long-running application server, a message pulled off a queue, or a job in a worker. Build the container once, then create a scope with Container::createScope(), resolve services from it as you would from the container, and dispose it when the unit of work ends:

Within a scope, services added with addScoped* methods resolve to one instance per scope, and every dependency in their graph is resolved from the scope, so transient services requested from a scope also receive the scope's scoped instances. Singleton services resolve to the same instance no matter which scope requests them, and their dependencies always resolve against the root container. A singleton that depends on a scoped service therefore fails with a ScopeException instead of capturing one scope's instance. When the scoped service is required (reachable through required edges alone), build validation catches this as a captive-dependency error before you ever call get(). A scoped service requested with no active scope (for example from inside a factory body) is something validation cannot predict, so it throws ScopeException at run time.

dispose() releases the scope's cached instances; any further request to the scope throws a ScopeException. Disposing a scope more than once has no effect.

Auto-binding

ContainerInterface and ScopeFactoryInterface are automatically added at build(), unless your own configuration already provides them, so most applications never add either explicitly:

A service that needs to open scopes of its own should depend on ScopeFactoryInterface rather than on the container:

Example: FrankenPHP worker mode

Application servers such as FrankenPHP keep the PHP process alive across many requests: the application (including the container and its singletons) boots once, and each incoming request is handled by a callback. Without the per-request teardown that PHP-FPM provided, any request-specific state held by a long-lived service silently leaks into subsequent requests. Creating a scope per request restores that isolation: scoped services live exactly as long as the request.

Run it with:

Every RequestHandler and any service in its dependency graph receives the current request's RequestContext; when dispose() runs, the scope's cached instances are released (and any that implement DisposableInterface have their dispose() method called), so nothing carries over into the next iteration of the loop. The same pattern applies to any long-running runtime (a RoadRunner or Swoole worker, a queue consumer, or a daemon), with the runtime's own receive loop in place of frankenphp_handle_request().

Disposing services

A service that holds a resource (a database transaction, an open file, a socket) often needs to release it deterministically when its lifetime ends, rather than waiting for garbage collection. A service can implement DisposableInterface to be notified:

When a resolution root (the container or a scope) is disposed, it calls dispose() on the disposable services it created, in reverse creation order so that dependents are disposed before their dependencies. build() itself constructs nothing, so only the services your application actually resolves are ever disposed:

The container disposes its own singletons (and any surviving transients it created) when the container itself is disposed:

After a container is disposed, any further get(), has(), or createScope() call throws a ContainerDisposedException. Disposing a container or scope more than once has no effect.

Opting out of disposal

By default the built container disposes every disposable instance it holds, including concrete instances you explicitly supply. When an instance's disposal is managed by something outside the container or if you intend to dispose it yourself, pass shouldDispose: false:

Lifetime and ordering guarantees

Scopes created from a container are managed by their own caller; dispose them before disposing the container so that their scoped instances are swept.

Adding services to the container

There are a number of built-in ways to specify how services should be resolved:

One method per lifetime covers all four, choosing the provider from the type of $source:

Use $shouldDispose: false to keep disposal responsibility for any service, supplied instance or not — see Opting out of disposal.

Specify the class name

Omit the source, and the container will construct the named class by calling the class's constructor, automatically resolving any dependencies in the constructor's parameter list.

In the following example, when the container provides an instance of MyService it will automatically inject all dependencies into its constructor to create an instance.

To do more than construct the class — decorate it, or configure it in a way the constructor cannot express — take the service's own type as a factory parameter. See Taking the autowired instance.

Specify an implementing class name

The container will provide the named service by resolving the named implementing subclass in its place.

[!IMPORTANT] You must also add the implementing class to the container as its own resolvable service, or build() will reject the configuration.

Pass the implementing class name as the source.

When your application requests an instance of HttpClient, the container will see that it should actually provide an instance of CurlHttpClient. It will then inject the CurlHttpClient constructor's dependencies to provide an instance.

Provide a factory callback

The container will resolve the named service by requesting it from the provided factory callback method. Any parameters in the factory method will be resolved automatically.

Pass any valid callable as the source: a closure, a first-class callable, a callable array such as [$producer, 'make'], a callable string such as 'Factory::create', or an invokable object.

[!CAUTION] A typo in a callable specified by a string will result in an error reporting an unresolvable implementation class by that name, rather than an error reporting an invalid function. This is because if the string is not a valid callable, the container will attempt to resolve it as a class name instead.

Inject a configuration value

When your application requests an instance of Mailer from the container, it will call the specified factory, injecting the AppConfig dependency. The factory then manually constructs an instance, specifying the mailer transport from that config.

Inline class implementation

Taking the autowired instance

A factory parameter that names the service the factory produces receives an instance with its constructor autowired as usual. This lets a factory configure or decorate a class without hand-writing its constructor arguments, preserving build-time verifiability.

The parameter is matched on its exact declared type plus its key, so a keyed service requires #[Key] on the parameter as well:

A union or intersection type never matches, even if one of its members resolves to the same service.

The instance is constructed once per resolution, so if several parameters name the service they all receive the same object.

The factory's return value will always be treated as the resolved service, even if it differs from the provided instance. Thus, a factory may wrap the instance it was handed with a decorator inheriting from the named service type rather than return it directly. The container will dispose the provided instance normally at the end of its lifetime.

[!NOTE] If the factory instead discards the provided instance, garbage collection will likely clean up the instance before the container can dispose it itself. In this case, if there is anything the class must always clean up, it should implement __destruct(), following the disposable pattern.

Provide a concrete instance

Pass the instance as the source and the container will resolve the service to it.

[!NOTE] Only addSingleton() and addKeyedSingleton() accept an instance: a provided instance is a single object, so it can only be a container-wide singleton.

Anytime your application requires a Request object, the container will provide the exact same instance that was passed in with the $request variable.

Keyed services

An application sometimes needs to provide the same type in more than one configuration. For example, you might want a separate Settings object for different areas of your application. Keyed services let you add multiple factories for a class under distinct keys and then retrieve or inject a specific one. Keys can be strings or enum values.

A keyed service is resolved only by its exact key. If the container has no service under the requested key, it will throw a ClassNotFoundException rather than falling back to the unkeyed service. A class may have both an unkeyed service and any number of keyed services since they are independent of one another.

The $source parameter accepts the same forms as the unkeyed add*() methods (see Adding services to the container). As with the unkeyed methods, only addKeyedSingleton() accepts an object instance.

Adding and retrieving keyed services

Injecting a keyed service

Apply the Key attribute to a constructor parameter to inject the service added under a specific key. As with get(), the lookup is absolute: if the container has no service under the key, it will throw a ParameterResolutionException.

Dependency injector

The library also provides Injector, a standalone dependency injector that calls functions and constructors directly, resolving their dependencies from a container. It can also inject explicit values for named or indexed parameters.

The following example injects dependencies into a controller method rather than its constructor.

Specifying dependencies

A function specifies its dependencies by listing them in its parameter list. A class specifies its dependencies by listing them in the parameter list of its constructor. Dependencies must be specified as either named object types, union types, or intersection types.

Named object types

If a dependency is specified as a named object type, the container will only provide a value if it can resolve a factory for that type.

Nullable types

If the container cannot resolve a dependency, but the dependency is nullable, then the container will provide a null value.

Builtin types with default values

The container is not able to resolve builtin types. However, if the function or class takes a builtin type and that parameter specifies a default value, the default value will be used.

To inject non-default values for builtin types, use a factory callback.

Union types

If a dependency is specified as a union type, the container will search sequentially through all named object types in the union list. It will provide a value using the first type it is able to resolve. Builtin types are ignored.

In the example above, the container will attempt to resolve an instance of HttpClient first. If it cannot resolve HttpClient, it will attempt to resolve an instance of GopherClient. If it cannot resolve GopherClient, it will ignore string and then throw a ParameterResolutionException.

Intersection types

If a dependency is specified as an intersection type, the container will attempt to fetch an instance of each type in the list until it finds one that satisfies all the types in the list. Since an instance must be retrieved in order to test whether it is a match, the use of intersection types may be slow and could have unintended consequences if the construction of any non-matching instances have side effects.

In the example above, the container will first attempt to resolve an instance of HttpClient. If it succeeds, it will check whether that instance is also Serializable and, if so, provide it. Otherwise, it will attempt to resolve Serializable and check whether that instance is also an HttpClient. If neither candidate satisfies both types, it will throw a ParameterResolutionException.

Lazy dependencies

Marking a parameter with the #[Lazy] attribute defers construction of that dependency until the injected object is first used, rather than when the consuming service is built. The injected value is a PHP lazy object of the resolved type, so it is instanceof the declared type and otherwise indistinguishable from an eagerly resolved instance. Its lifetime, identity, and disposal are those of the underlying service; a lazy singleton is still a single shared instance.

Here PdfRenderer (and everything it depends on) is not constructed when ReportController is resolved, but the first time a property or method of $renderer is accessed. #[Lazy] applies to constructor and factory parameters, except for a factory parameter naming the service the factory produces, which the container constructs directly.

Because a lazy dependency is not constructed while its consumer is, #[Lazy] also breaks an otherwise-fatal construction cycle between two services: mark one edge of the cycle lazy and both services resolve.

The container constructs the lazy object in one of two ways, chosen automatically:

For the container to build either, the dependency's concrete class must be known at build time and must declare at least one property (PHP has no state to defer for a property-less class). A factory-produced service qualifies when its added class or its declared return type is a concrete class. When neither holds, build() reports the #[Lazy] parameter as a build error rather than resolving it eagerly.

The standalone Dependency injector also honors #[Lazy]. A proxy needs a concrete class up front, so the injector takes it from the parameter's own type when it is a concrete class. For an interface-typed parameter it asks the backing container for the concrete class it resolves to. If the backing container cannot report it, or the service has no statically known concrete class, the #[Lazy] parameter throws an InjectorException.

Error handling

Every exception the library throws extends Suhock\DependencyInjection\DependencyInjectionException.

These exceptions all extend RuntimeException: they signal a container that was misconfigured or misused, whether the problem shows up at build time or at run time, not a bug inside the library itself.

The base class is DependencyInjectionException. Notable subclasses include:

When dependency-injection exceptions are chained through a resolution graph, they are consolidated into a single message; the original exception remains available via getConsolidatedException(). ContainerValidationException does not chain a previous exception; its issue list carries every problem found instead.

Caching compiled plans

build() compiles and validates the configuration into resolution plans (see Build performance). A cache lets those plans be stored under a fingerprint of the configuration and reused by later build() calls of the same configuration, which matters on a per-request lifecycle such as PHP-FPM where build() would otherwise run on every request.

ContainerBuilder::createDefault() accepts an optional cache:

Suhock\DependencyInjection\Cache\CacheInterface is a minimal key/value store with two methods:

tryGet() returns whether the id was present and populates $value by reference. Reporting presence through the return value means a stored null or false is not mistaken for a miss.

Suhock\DependencyInjection\Cache\ApcuCache implements CacheInterface using the APCu extension. Its entries live in shared memory and persist across requests served by the same worker pool. The constructor throws a RuntimeException if the apcu extension is not loaded and enabled.

Suhock\DependencyInjection\Cache\OpcacheCache implements CacheInterface by writing each entry as a PHP file in a directory and loading it with include, so OPcache keeps the compiled entry in shared memory. OPcache ships with PHP but is not always enabled; without it, compiling the file costs about as much as compiling the graph, so use ApcuCache where OPcache is off. The constructor takes the directory to write to, creating it if missing, and throws a RuntimeException if it cannot be created or is not writable.

The directory must be one the application owns, such as a var/cache path inside the project, never a shared temp directory, because the included files execute as code; this is why there is no default. Each distinct configuration adds a file rather than replacing one, so the directory should be cleared on deploy.

Consumers can also implement CacheInterface themselves to back the cache with another store.

Appendix

PSR-11 compatibility

This library's Container::get() takes a class name and optional key rather than PSR-11's opaque string id, so Container does not and should not implement Psr\Container\ContainerInterface directly.

For frameworks that expect a PSR-11 container, the suhock/dependency-injection-psr11 package provides a thin adapter that wraps the container and translates its exceptions into their PSR-11 counterparts.

PHPStan extensions

PHPStan extensions for this library are published in the separate suhock/dependency-injection-phpstan package. Add it as a dev requirement.


All versions of dependency-injection with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
suhock/disposable Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package suhock/dependency-injection contains the following files

Loading the files please wait ...