October 23, 2024
Chicago 12, Melborne City, USA
PHP

How to inject service dependencies in a Factory Method while passing custom parameters in Laravel?


I would like to create a service using the factory method design pattern. So I created the following product:

class ActivityReport
{
    private $activityService;

    public function __construct(Customer $customer, ActivityService $activityService)
    {
        $this->activityService = $activityService;
    }

    public function getData()
    {
        // It will be more code
        return $this->activityService->getAll($this->customer->id);
    }
}

And I’m calling it in this way:

class ActivityReportCreator extends ReportCreator
{
    private $customer;

    function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }

    public function generate() {
        $activity = new ActivityReport($customer->id);
        return $activity->getData();
    }
}

The issue here is with the constructor in the product, which accepts a service via DI (Dependency Injection) that should be automatically loaded, as it typically happens with services or controllers. The activityService has been registered and works, for example, in controllers. I can run it using app(ActivityReport::class), but first of all, I would still need to pass the $customer object not to the constructor, but to the method. Secondly, I want to consistently reference the service everywhere, just like it’s done in the case of controllers.

How can I achieve this?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video