如何在 Symfony 中调用其他服务?

Posted

技术标签:

【中文标题】如何在 Symfony 中调用其他服务?【英文标题】:How to call to another services in Symfony? 【发布时间】:2015-02-01 19:47:20 【问题描述】:

我遇到了这样的问题 我得到了一项服务来注入教义并使用实体管理器将用户记录插入数据库:UsersService.php

我得到了一个发送电子邮件的服务:MyEmailService.php

在 services.yml 中注入的所有两种服务(请关注此文档http://symfony.com/doc/current/book/service_container.html)。它们都工作正常。

所以现在我的问题是:我有一个类调用 UserFacade.php(不扩展任何控制器)。它有一个方法“addUser”。在此函数中,它将调用 UserService.php 将记录插入数据库,然后调用 MyEmailService.php 将电子邮件发送到用户的电子邮件。 我如何在 Symphony 中做到这一点?我是 Symphony 中捆绑包的新手。

请帮忙 谢谢

【问题讨论】:

您是否尝试过将类本身包含到控制器中? 是的@MikeAnte。我的问题是如何从 UserService 调用教义管理器?然后从 UserFacade 调用 UserService 【参考方案1】:

首先你必须declare your dependencies in the constructor UserFacade 类。这是允许 symfony 注入依赖项的一种方法:

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, ...);
    

然后你必须在你的 service.yml 中声明依赖项(假设你使用 YAML,XML 非常相似):

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

然后在你的控制器中使用外观:

class UserController 

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

【讨论】:

【参考方案2】:

您必须将您的 UserFacade 类注册为服务,将 UserService(和 MyEmailService)注入其中。然后从 UserFacade 服务中调用 UserService 和 MyEmailService 作为属性:

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

【讨论】:

以上是关于如何在 Symfony 中调用其他服务?的主要内容,如果未能解决你的问题,请参考以下文章

Symfony:我如何在 Messenger 中使用远程过程调用(RPC)?

如何在 Symfony2 中创建 cron 任务

如何在 symfony phpunit kernelTestCase 中正确注入 monolog.logger / LoggerInterface 作为模拟

如何在 Symfony2 控制器中获取用户 IP 地址?

如果已经在其他应用程序中登录主域,如何使用 symfony 安全登录到子域?

如何在 symfony 2 中获取根路由