PhunkB
PhunkB

Reputation: 25

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

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.

Upvotes: 1

Views: 954

Answers (3)

Rufinus
Rufinus

Reputation: 30731

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(PaymentService $paymentService, Request $request): Response
    {
        $id = $request->get('id');
        $payment = $paymentService->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.

Upvotes: 1

Bhavin Nakrani
Bhavin Nakrani

Reputation: 532

You have to inject service directly in controller and do data validation in PaymentService. For example:

class MyController extends AbstractController 
{
    private PaymentRequestService $paymentRequestService; 
    public function __construct(PaymentRequestService $paymentRequestService)
    {
       $this->paymentRequestService = $paymentRequestService;
    }
    
    public function index()
    { 
       $this->paymentRequestService->method();
    }     
}

Upvotes: 0

n.h
n.h

Reputation: 1

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.

Upvotes: 0

Related Questions