Skip to content
This repository was archived by the owner on Jan 16, 2019. It is now read-only.

Default implementations

Frank Kleine edited this page May 28, 2015 · 2 revisions

Default implementations

Very often you only use one concrete implementation of an interface in your application and only added the interface or abstract class to make dependent classes better testable. To avoid having to bind all of your interfaces to the concrete implementations you may specify a default implementation which will be used. To achieve this, add the @ImplementedBy annotation to your interface.

/**
 * All Persons should be bound to the class Schst unless Person is bound
 *
 * @ImplementedBy(Schst.class)
 */
interface Person {
    public function sayHello();
}


$person = $injector->getInstance('Person'); // $person is now an instance of Schst

It should be noted though, that once a specific binding for Person is added to the binder that the annotation is not considered anymore:

$binder->bind('Person')->to('Mikey);
$person = $binder->getInjector()->getInstance('Person');

In this example, $person is now an instance of Mikey and not of Schst - the explicit binding overruled the annotated binding.

Default implementations per runtime mode

Available since release 6.0.0

Sometimes it is required to have a different default implementation per runtime mode, e.g. a mock implementation for DEV and the real service implementation for PROD. This can be accomplished by specifying a mode:

/**
 * @ImplementedBy(mode="DEV", class=Mikey.class)
 * @ImplementedBy(Schst.class)
 */
interface Person {
    public function sayHello();
}

Now, depending on the runtime mode, the according implementation will be chosen. If the runtime mode is DEV, an instance of Mikey will be created, and Schst for all other runtime modes.

Please note that you should always specify one default without a runtime mode, otherwise a stubbles\ioc\binding\BindingException will be thrown in case no implementation can be found for the current runtime mode.

Clone this wiki locally