【问题标题】:How to call to another services in Symfony?如何在 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

标签: php symfony doctrine-orm


【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 2015-12-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2011-05-04
      • 2018-10-03
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多