Skip to content

Service Definitions

A service definition is a plain description of how to build one service: its class name, the constructor arguments, and any method calls to make afterwards. It deliberately knows nothing about the container around it — not the name the service is registered under, nor whether it will be shared or rebuilt each time. That separation is what lets the same definition be reused, compiled, or handed to a factory.

You may reach for definitions directly when you want to describe services in PHP rather than in a .ctn file — for example when building a container from your own data source. The package ships with a ready implementation of ServiceDefinitionInterface, simply called ServiceDefinition.

Constructor

Construct a new service definition with the given classname and optional arguments as array.

Method definition:

php
final public function __construct(string $className, array $arguments = [])

Arguments

Data typeVariable nameComment
class-string$classNameThe full class name of the desired service.
array<mixed>$argumentsAn array of constructor arguments for the service.

Create a new service definition:

php
use ClanCats\Container\ServiceDefinition;

$logger = new ServiceDefinition(MyLogger::class);

You can also directly pass the constructor arguments as an array:

php
$logger = new ServiceDefinition(MyLogger::class, ['@some_dependency', ':some_parameter', 42]);

Keep in mind when passing arguments as an array prefixing a string with @ will be interpreted as a dependency and : as parameter. This applies everywhere arguments are defined as array. Service Arguments

Static factory

There is also a static method to construct new service definition instance allowing a more expressive syntax.

Static instance constructor to allow eye candy like:

php
ServiceDefinition::for('\Acme\SessionService')
   ->addDependencyArgument('storage')
   ->addParameterArgument('session_token')
   ->addRawArgument(600)

Or the shorter way

php
ServiceDefinition::for('\Acme\SessionService', ['@storage', ':session_token', 600])

Method definition:

php
public static function for(string $serviceClassName, array $arguments = []): self

Arguments

Data typeVariable nameComment
class-string$serviceClassNameThe full class name of the desired service.
array<mixed>$argumentsAn array of constructor arguments for the service.

Returns

static

Construct from array

Construct a single service definition object from an array

php
ServiceDefinition::fromArray([
    'class' => '\Acme\Demo',
    'arguments' => ['@foo', ':bar'],
    'calls' => [
        ['method' => 'setName', [':demo.name']]
    ]
])

Method definition:

php
public static function fromArray(array $serviceConfiguration)

Arguments

Data typeVariable nameComment
array<mixed>$serviceConfiguration

Returns

static

Constructor Arguments

You can pass additional constructor arguments any time:

php
$QA = new ServiceDefinition(QA::class);

$QA
    ->addRawArgument('The Answer to the Ultimate Question of Life, The Universe, and Everything.')
    ->addRawArgument(42)
    ->addDependencyArgument('database')
    ->addParameterArgument('priority.default');

Using the arguments method you can also pass them as an array.

php
$auth = (new ServiceDefinition(MyAuth::class))
    ->arguments([
        '@repository.users',
        ':auth.secret'
    ]);

Add raw argument

Add a simple raw constructor argument.

Method definition:

php
public function addRawArgument($argumentValue) : ServiceDefinition

Arguments

Data typeVariable nameComment
mixed$argumentValue

Returns

self

php
$def = ServiceDefinition::for('\Acme\SqlConnection')
    ->addRawArgument('localhost')
    ->addRawArgument('root')
    ->addRawArgument('pleaseDontUseRoot');

Add dependency argument

Add a dependency constructor argument.

Method definition:

php
public function addDependencyArgument($argumentValue) : ServiceDefinition

Arguments

Data typeVariable nameComment
mixed$argumentValue

Returns

self

php
$def = ServiceDefinition::for('\Acme\Blog\PostRepository')
    ->addDependencyArgument('db.connection');

Add parameter argument

Add a simply parameter constructor argument.

Method definition:

php
public function addParameterArgument($argumentValue) : ServiceDefinition

Arguments

Data typeVariable nameComment
mixed$argumentValue

Returns

self

php
$def = ServiceDefinition::for('\Acme\Session')
    ->addParameterArgument('session.secret');

Get all arguments

Returns the constructor arguments object

Method definition:

php
public function getArguments() : ServiceArguments

Arguments

This method takes no arguments.

Returns

ServiceArguments

php
$definition->getArguments(); // ServiceArguments instance

Get service class name

Returns the service class name

Method definition:

php
public function getClassName() : string

Arguments

This method takes no arguments.

Returns

class-string

Method Calls

A service definition can hold method calls that have to be called on construction, these can set dependencies, parameters or raw values just like the constructor arguments.

Add a method call (with array)

Adds a method call to the service definition, the arguments should be set as an array.

Method definition:

php
public function calls(string $method, array $arguments = []) : ServiceDefinition

Arguments

Data typeVariable nameComment
string$methodThe name of the method to be called.
array<mixed>$argumentsThe method arguments as array.

Returns

self

php
$def = ServiceDefinition::for('\Acme\Session')
    ->calls('setEventDispatcher', ['@event_dispatcher']);

Add a method call

Adds a method call to the service definition, the arguments must be set with a ServiceArguments instance.

Method definition:

php
public function addMethodCall(string $methodName, ServiceArguments $arguments) : ServiceDefinition

Arguments

Data typeVariable nameComment
string$methodNameThe name of the method to be called.
ServiceArguments$argumentsAn `ServiceArguments` instance for the method call.

Returns

self

php
$eventDispatcherArgs = (new ServiceArguments())
    ->addDependency('event_dispatcher');

$sessionDefinition = ServiceDefinition::for('\Acme\Session')
    ->addMethodCall('setEventDispatcher', $eventDispatcherArgs);

Interface

Any class that will be used as a service definition must implement the ServiceDefinitionInterface which requires the following methods:

Return the service class name

php
public function getClassName() : string;

Return the constructor arguments object

php
public function getArguments() : ServiceArguments;

Return the registered method calls

php
public function getMethodCalls() : array;

The format of the returned array should look like [string => ServiceArguments].