Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2/3 Get Classes in Directory that Implement an Interface

Tags:

php

symfony

Is there a nice way in Symfony 2 or 3 to load all classes within a directory that implements a particular interface?

like image 897
nfplee Avatar asked Oct 16 '25 01:10

nfplee


1 Answers

Since Symfony 3.3/3.4 it is possible by using configuration only (without a need to write custom CompilerPass):

# config/services.yaml
services:
# ...

_instanceof:
    App\HandlerInterface:
        tags: ['app.handler']

App\HandlerCollection:
    # inject all services tagged with app.handler as first argument
    arguments: [!tagged app.handler]

and if you need to restrict services to register from a single directory see importing with resource

references:

  • https://symfony.com/doc/current/service_container/3.3-di-changes.html#auto-configure-with-instanceof
  • https://symfony.com/doc/3.4/service_container/tags.html#reference-tagged-services
  • http://symfony.com/doc/3.4/service_container.html#importing-many-services-at-once-with-resource
like image 62
kaznovac Avatar answered Oct 18 '25 17:10

kaznovac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!