Home > Blockchain >  How to call a method service injected in another constructor service PHP Symfony
How to call a method service injected in another constructor service PHP Symfony

Time:05-18

So I'm really trying to figure it out how can I do that in Symfony 5.

I have an services named PaymentRequestService which have the entire logic for requests to another application (based on microservices). I injected PaymentRequestService in PaymentService as constructor, an service which processes data, make validation, etc.

And right now I'm trying to call from my controller an method from PaymentRequestService by using PaymentService. Something like that: $paymentService->$paymentRequestService->method.

Can someone tell me how can I do that?

Right now it looks something like that $payment = $paymentRequestService->getPaymentRequest((string)$id) But I want to eliminate PaymentRequestService.

CodePudding user response:

That should be doable over a getter like you have implemented currently, but why not just pass the PaymentRequestService to the controller where it is used? e.g. $paymentRequestService->method()

Services are injectable in every class inside your application and since there is (by default) only one instance of that service running, you could just autowire it to your controller.

CodePudding user response:

I dont argue the architecture you want to use... but you would do it this way: (PHP 8 syntax)

class PaymentService

    public function __construct(private PaymentRequestService $requestService)
    {}
  
    public function getRequest(): PaymentRequestService
    {
         return $this->requestService;
    }
}


class MyController extends AbstractController 
{
    public function myAction(RequestService $requestService, Request $request): Response
    {
        $id = $request->get('id');
        $payment = $requestService->getRequest()->getPaymentRequest((string)$id);

        return new Response('done');
    } 

}

you also could map specific methods to dont need the cascading - but then why you dont use the RequestService directly in the first place.

  • Related