ClanCats Logo

Container

Service Binding Basics

A Container instance compiled or not, is always able to bind new or override existing services dynamically during your application runtime. This also allows us to define Closure callbacks as service factories.

Keep in mind that in the below examples following namespaces are used:

use ClanCats\Container\{
    Container,
    ServiceFactory  
};

Bind method

The Containers bind method acts as a shortcut and supports three diffrent argument types:

  • ServiceFactoryInterface instance.
  • Closure callback.
  • Classname represented as string.

Binds a service factory to the container.

$container->bind('session', new SessionFactory);
$container->bind('config', function($c) {
     return new Config($c->get('config.loader'));
}, false);
$container->bind('router', '\\Routing\\Router')
    ->addDependencyArgument('config');

Method definition:

public function bind(string $name, $factory, bool $shared = true)

Arguments

Data type Variable name Comment
string $name The service name.
mixed $factory The service factory instance, the closure or the classname as string
bool $shared Should the service be shared inside the container.

Returns

Closure, ServiceFactoryInterface The given or generated service factory.


Bind ServiceFactoryInterface

The ServiceFactoryInterface demnads only a create method to retrieve the expected service. This package comes with a prebuild ServiceFactory class allowing you to construct a service from a ServiceDefinition or basically by his classname.

Note: Check Service Factories for more.

$sessionFactory = new ServiceFactory('\\Acme\\Session', ['@session.provider.mysql']);

$container->bind('session', $sessionFactory);