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

Map bindings

mikey179 edited this page Jul 30, 2012 · 5 revisions

Map bindings

Map bindings are almost the same as List-Bindings, but while list bindings are kind of anonymous (you can see them as indexed arrays) map bindings allow for named values (which compares to associative arrays). The functionality of map bindings is identical to list bindings, this includes typed and untyped map bindings. The only difference is the @Map annotation and how map bindings are created with the binder:

class PluginManager
{
    private $plugins;

    /**
     * @Inject
     * @Map(example\Plugin.class)
     */
    public __construct($plugins)
    {
        $this->plugins = $plugins;
    }

    // Methods for managing plugins
}

Bindings can be defined as follows:

$binder->bindMap('example\Plugin')
       ->withEntry('security', new SecurityPlugin())  // alternatively: ->withEntry('security', 'example\\SecurityPlugin')
       ->withEntryFromProvider('coolStuff', 'example\\CoolPluginProvider'); // provides AnotherCoolPlugin

Closure bindings

Starting with release 2.1.0 it is also possible to bind values using closures:

$binder->bindMap('example\Plugin')
       ->withEntryFromClosure('extended', function() { return EvenMoreSecurityPlugin(); });

This comes in handy when a value should be initialized lazy because it's too much effort to create it at the very moment, but using a separate injection provider would be overblown. The code inside the closure has to create the value, it doesn't have any access to the injector, so if there any dependencies they must be available at the moment the closure is created.

Clone this wiki locally