简体   繁体   中英

How to call to another services in Symfony?

I got a problem like this I got a service to inject doctrine and use the entity manager to insert a user record into database: UsersService.php

And i got a service to send email: MyEmailService.php

All both services injected in the services.yml(follow this docs http://symfony.com/doc/current/book/service_container.html ). All of them work fine.

So now my problem is: I have a class call UserFacade.php( not extends any controller ). It has a method "addUser". In this function it will call to UserService.php to insert a record into database, then call the MyEmailService.php to send an email to user's email. How can i do that in Symphony? I'm the newbie with bundle in Symphony.

Please help Thanks

First you have to declare your dependencies in the constructor of the UserFacade class. This is one way to allow symfony to inject the dependencies:

class UserFacade 
{
    /** @var UserService */
    private $userService;

    /** @var EmailService */
    private $emailService;

    public function __construct(UserService $userService, MyEmailService $emailService) 
    {
        $this->userService = $userService;
        $this->emailService = $emailService;
    }

    public function addUser(User $user) 
    {
        $this->userService->add($user);
        $this->emailService->sendUserMail($user, ...);
    }
}

Then you have to declare the dependencies in your service.yml (assuming your using YAML, XML is quite similar):

services:
    user_service:
        class:     UserService
        ...
    email_service: 
        class:     EmailService
        ...
    user_facade:
        class:     UserFacade
        arguments: [@user_service, @email_service]

And then use the facade in your controller:

class UserController 
{
    public function addUserAction(Request $request) 
    {
        // Do stuff with Request to populate the $user object
        $this->get('user_facade')->addUser($user);
    }
}

You have to register your UserFacade class as a service, inject into it UserService (and MyEmailService). Then call UserService and MyEmailService from UserFacade service as a property:

$this->userService-><methid>
// and so on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM