Skip to content
This repository was archived by the owner on Nov 9, 2022. It is now read-only.

Array of services injection - #2

Open
jakubkulhan wants to merge 3 commits into
kutny:masterfrom
jakubkulhan:master
Open

Array of services injection#2
jakubkulhan wants to merge 3 commits into
kutny:masterfrom
jakubkulhan:master

Conversation

@jakubkulhan

Copy link
Copy Markdown

When array is "type hinted", autowiring looks if type is specified in doc comment and wires array of all matching services.

E.g.

interface SlugRepositoryInterface {
    function getBySlug($slug);
}

class FooRepository implements SlugRepositoryInterface {
    public function getBySlug($slug) { ... }
}

class BarRepository implements SlugRepositoryInterface {
    public function getBySlug($slug) { ... }
}

class SlugTrailService {

    /** @var SlugRepositoryInterface[] */
    private $repositories;

    /**
     * @param SlugRepositoryInterface[]
     */
    public function __construct(array $repositories) {
        $this->repositories = $repositories;
    }

    public function findAllBySlug($slug)
    {
        return array_map(function (SlugRepositoryInterface $r) use ($slug) { return $r->getBySlug($slug); }, $this->repositories);
    }
}

@kutny

kutny commented Apr 12, 2014

Copy link
Copy Markdown
Owner

Hi, thank you for this idea. What happens if I need services in that array in some specific order? How can I do it? Only by wiring them manually? What if I do not need to pass all services that implement SlugRepositoryInterface to SlugTrailService?

I'm not sure, but this approach seems too magical to me.

@jakubkulhan

Copy link
Copy Markdown
Author

The idea came from Spring Framework, where IoC container can autowire List<T> arguments. In use cases I have encountered in Java, order wasn't either important, or order was clearly defined by return of one of their methods, so sorting passed in list solved it.

About the latter question, the interface servers here as a marker - I can't think of any case where I would make service implement such interface and then wouldn't want to have it injected :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants