Skip to content

Latest commit

 

History

History
88 lines (64 loc) · 1.54 KB

service-container.md

File metadata and controls

88 lines (64 loc) · 1.54 KB

Service container

The service container is an implementation of Dependency Injection pattern. It manages the instantiation of objects (services).

Create a service

By default, the service container looks into bundles a YAML file services.yml. It is used to define services.

For example:

services:
    # My service named "my_service"
    my_service:
        class: "Path/To/MyService"

    # Foo
    foo:
        class: "Path/To/Foo"
        arguments:
            - "a"
            - "b"

The class paths are relative to bundle path.

Now in your code, you can retrieve the service like this:

let foo = container.get("foo");
let sameFoo = container.get("foo");

A service is instantiated once.

Arguments

You can define constructor arguments with the keyword arguments. Each argument is treated as a primitive like string, number or array.

Example:

services:
    my_service:
        class: "Path/To/MyService"
        arguments:
            - "foo"
            - 42
            - ["a", "b"]

You can also inject another service as an argument by prefixing the name with @:

services:
    my_service:
        class: "Path/To/MyService"
        arguments:
            - "@foo"

    foo:
        class: "Path/To/MyService"

Service from a factory

You can also define a service with a factory.

Example:

services:
    my_service:
        factory: ["@my_factory", create]
        arguments:
            - "foo"
            - 42