dereuromark / cakephp-queue

Queue plugin for CakePHP - simple, pure PHP and without dependencies.
MIT License
306 stars 137 forks source link

Is it possible to use the DI Container inside a task? #324

Closed LordSimal closed 2 years ago

LordSimal commented 2 years ago

With that I wouldn't need to manually create service objects inside the task 😄

dereuromark commented 2 years ago

Can you make a draft how that would look like?

LordSimal commented 2 years ago

Variant 1: Well I though the easiest way would be to make it behave the same as commands get their services injected - via the constructor. But as I just saw this would mean users would have to pass the $io and $logger object to the parent constructor so this may not be the easiest variant from a usage perspective.

Variant 2: Another way would be to inject services into the run() method just like Cake does inject services into controller actions which basically happens here: https://github.com/cakephp/cakephp/blob/4.x/src/Controller/ControllerFactory.php#L157 But I have no idea how to implement that for the run() method - currently.

Variant 3: Even though I haven't looked that deeply into the league/container implementation I thought of maybe adding another extra method which is just there for injection purposes. So something like

public function services(UserService $userService): void
{
    $this->userService = $userService;
}

which gets called after the Task has been created but before the the run() method has been executed. So basically right before: https://github.com/dereuromark/cakephp-queue/blob/d46358e97e9220ae1a5649d5d29a7dc0fc8105c6/src/Queue/Processor.php#L189

dereuromark commented 2 years ago

Sounds like v3 could be done as PR and we can see how that could be finished.