Aliases are a way to tell Hiraeth’s dependency injector which concrete classes should be injected for which interfaces.
If we review our example for creating a delegate, we created Bar
using a delegate in order to inject some necessary confguration value during construction. In this example, we can imagine that Bar
now implements BarInterface
. Rather than typehinting Bar
directly, we may want to receive it when we typehint the interface as such:
class MyAction
{
public function __construct(BarInterface $bar)
{
$this->bar = $bar;
}
}
In order to achieve this, we will register Bar
as an alias for BarInterface
. We can register the alias in any config file under the [application]
section. Hiraeth scans all [application]
sections on startup and registers the aliases with the dependency injector.
[application]
aliases = {
"BarInterface": "Bar"
}
Now, when the dependency injector attempts to create MyAction
above, it will first look up if there is a concrete class aliased to BarInterface
, construct that class using its delegate if it exists, and inject it.
You do not need delegates to create aliases. Any interface can be aliased to any class and the dependency injector will attempt to construct that class as it normally would, i.e. it will use a delegate if one exists, but will try to construct it without one if not. Additionally, just like other injected dependencies, the instance will be passed to any applicable providers prior to injection.
Pseudo-Interfaces and Fallback Classes
If you register an alias for a non-existent interface, Hiraeth will register a PHP class alias and add that alias to the dependency injector. This can be useful in cases where you might want to offer an existing concrete implementation without a real interface and migrate to an actual interface later on.
This functionality also allows you to create what amounts to a fallback class since the class alias is only registered if the interface / class name does not point to a real class. Using hiraeth/bootstrap
, for example, Hiraeth\Actions\AbstractAction
is aliased by AbstractAction
(in the root namespace):
aliases = {
"AbstractAction": "Hiraeth\Actions\AbstractAction"
}
The above entry allows any actions you create to simply extend AbstractAction
rather than Hiraeth\Actions\AbstractAction
. Additionally, if you choose at a later date to create a real AbstractAction
to extend Hiraeth’s, the alias simply will not be registered and your actions will automatically be extending the newly created class.