0

How can I directly create an object instance in a certain way? This object is a task handler, the processor of each task may be different. Is it similar to the method of Yii::createObject(). I don’t want to register handlers in service.yarml, because there may be many handlers.

Here is what I would like to acheive:

$task = new Task;
// $handler = $this->container->get($task->getHandlerName()); 
$handler = createObject($task->getHandlerName());
$handler->handle($task);
// Handler

class MyHandler {
     private $manager;

      // autowiring
     public function __construct(EntityManagerInterface $manager) {
            $this->manager = $manager;
     }
     public function handle() {

     }
}
Richard-Degenne
  • 2,892
  • 2
  • 26
  • 43
Sizhao
  • 1
  • Although it's not completely clear what you want, I suspect you want a ServiceLocator or ServiceSubscriber https://symfony.com/doc/current/service_container/service_subscribers_locators.html - if your handler names are all fully qualified class names, it's easier and your container line may actually work. I can't find it specifically, but you can inject all classes implementing a certain interface into a service, which would then theoretically be able to provide these as handlers via some mechanism to determine the mapping name -> class. – Jakumi Sep 01 '20 at 06:18
  • to reiterate ... [tagged services](https://symfony.com/doc/master/service_container/tags.html) is probably what you want, however, you have to find a way to tag all handlers, maybe via a compiler pass. – Jakumi Sep 01 '20 at 06:52
  • Here is an example of a [Service Locator](https://stackoverflow.com/questions/54946647/get-service-via-class-name-from-iterable-injected-tagged-services/54949631#54949631) implementation. Assuming your handlers all implement a HandlerInterface then there would be no need to explicitly list handlers in services.yaml. – Cerad Sep 01 '20 at 12:11

0 Answers0