Skip to content

Create a service locator for tests #8699

Closed
@nicolas-grekas

Description

@nicolas-grekas

During SymfonyCon workshop, someone asked: now that we have ServiceSubscriberInterface, how can I test a service that consumes a PSR-11 container?

Here is a snippet that allows creating a dedicated service locator, might be useful somewhere in the doc:

use Symfony\Component\DependencyInjection\ServiceLocator;

$container = new class() extends ServiceLocator
{
    private $services = [];

    public function __construct()
    {
        parent::__construct([
            'foo' => function () {
                return $this->services['foo'] = $this->services['foo'] ?? new stdClass();
            },
            'bar' => function () {
                return $this->services['bar'] = $this->services['bar'] ?? $this->createBar();
            },
        ]);
    }

    private function createBar()
    {
        $bar = new stdClass();
        $bar->foo = $this->get('foo');

        return $bar;
    }
};

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions