WooCommerce Code Reference

Container
in package

A simple Dependency Injection Container

This is used to manage dependencies used throughout the plugin.

Tags
since
2.5.0

Table of Contents

$registry  : array<string|int, AbstractDependencyType>
A map of Dependency Type objects used to resolve dependencies.
factory()  : FactoryType
Public api for adding a factory to the container.
get()  : mixed
Interface for retrieving the dependency stored in the container for the given identifier.
register()  : mixed
Interface for registering a new dependency with the container.

Properties

Methods

factory()

Public api for adding a factory to the container.

public factory(Closure $instantiation_callback) : FactoryType

Factory dependencies will have the instantiation callback invoked every time the dependency is requested.

Typical Usage:

$container->register( MyClass::class, $container->factory( $mycallback ) );
Parameters
$instantiation_callback : Closure

This will be invoked when the dependency is required. It will receive an instance of this container so the callback can retrieve dependencies from the container.

Return values
FactoryTypeAn instance of the FactoryType dependency.

get()

Interface for retrieving the dependency stored in the container for the given identifier.

public get(string $id) : mixed
Parameters
$id : string

The identifier for the dependency being retrieved.

Tags
throws
Exception

If there is no dependency for the given identifier in the container.

Return values
mixedTypically a class instance.

register()

Interface for registering a new dependency with the container.

public register(string $id, mixed $value) : mixed

By default, the $value will be added as a shared dependency. This means that it will be a single instance shared among any other classes having that dependency.

If you want a new instance every time it's required, then wrap the value in a call to the factory method (@see Container::factory for example)

Note: Currently if the provided id already is registered in the container, the provided value is ignored.

Parameters
$id : string

A unique string identifier for the provided value. Typically it's the fully qualified name for the dependency.

$value : mixed

The value for the dependency. Typically, this is a closure that will create the class instance needed.

Return values
mixed