D
D
Danbka2021-12-08 14:56:06
PHP
Danbka, 2021-12-08 14:56:06

How can a service select the required repository at runtime?

Hey!

I will say that the given code examples are abstract, but help to understand the problem that I encountered.

There is a controller that calls a method on some service:

class ExampleController extends AbstractController
{
    public function index(SomeService $service)
    {
        ...
        $service->getResult('paramValue');
        ...
    }
}


Now the service itself:
class SomeService
{
    public function getResult(string $param)
    {
        ...
        $epics = $this->repository->getData();
        ...
    }
}


And there are 2 repositories that implement one interface:

interface DataRepository {
    public function getData();
}

class RepositoryOne implements DataRepository {
    private $external;
    public function __construct(ExternalService $external)
    {
        $this->external = $external;
    }

    public function getData()
    {
        ...
    }
}

class RepositoryTwo implements DataRepository {
    private $external;
    public function __construct(ExternalService $external)
    {
        $this->external = $external;
    }
    public function getData()
    {
        ...
    }
}


The catch is that the service should get data from the repository, but from which one it depends on the $param parameter passed.

I can not figure out how to instantiate the object of the desired repository in this case? If directly to the service, then in the service you will also have to inject ExternalService in order to pass it to the getData method, which SomeService in general should not know about (high class connectivity is obtained).

Anticipating questions about what kind of nonsense is going on here, I can say that ExternalService is an external service that I cannot influence, and in which the user data of interest to me is stored in different columns of the table depending on the user group.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Derepko, 2021-12-08
@uDenX

https://github.com/symfony/symfony/blob/6.0/src/Sy...
https://designpatternsphp.readthedocs.io/ru/latest...
Either shift the choice to the repositories themselves, or introduce a new class, who will choose

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question