Skip to content

DiFactory attribute ​

Declaration via the \Kaspi\DiContainer\Attributes\DiFactory attribute is implemented using the Factory pattern [1]. This attribute registers a PHP class within the container or injects a dependency into a parameter of a method or a callable type [2].

Attribute configuration:

  • \Attribute::TARGET_CLASS
  • \Attribute::TARGET_PARAMETER
  • \Attribute::IS_REPEATABLE

Attribute signature:

php
\Kaspi\DiContainer\Attributes\DiFactory::__construct(
    string|array $definition,
    ?bool $isSingleton = null,
    array $arguments = []
)

Parameters:

  • $definition – FQCN[3] and method name.
  • $isSingleton – The container will return the same object instance (singleton pattern). If set to null, the value will be determined based on the container configuration.
  • $arguments – arguments for the factory method.

TIP

Read the documentation section “Using factory methods for dependency injection”.

Factory method arguments ​

The $arguments parameter of the \Kaspi\DiContainer\Attributes\DiFactory attribute specifies how dependencies should be injected into specific parameters of a PHP "factory" class method.

When declaring dependency injection for a specific parameter, use the name of that parameter as the array key within $arguments.

Parameters that do not receive arguments via $arguments will be injected by the container automatically, based on the configuration.

You can use classes from other container definitions within the arguments.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionAutowire – PHP class.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionCallable – injects a dependency by invoking a callable type.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionFactory – factory for dependency injection.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionGet – dependency injection via a reference to a container identifier.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionParameter – dependency injection from container parameters.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionParameterRutime – dependency injection from runtime container parameters.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionProxyClosure – dependency injection via "lazy loading".
  • Kaspi\DiContainer\DiDefinition\DiDefinitionRuntime – runtime object injection.
  • Kaspi\DiContainer\DiDefinition\DiDefinitionTaggedAs – dependency injection - collection by tag.

  1. In some scenarios, it becomes necessary—for the purpose of dependency injection—to employ the "factory" design pattern, delegating the creation of a required object to a dedicated PHP class known as a "factory." ↩︎

  2. The callable type represents values ​​or expressions that can be invoked as a function. See the description in the PHP documentation. ↩︎

  3. Fully Qualified Class Name – the full name of a class or interface, including its namespace. ↩︎