Symfony 4 - 私人外部服务的最佳实践

psy*_*o66 5 service private external public symfony4

我已经安装了 Symfony 4 的最新版本,它真的很棒!

但是当我们在您的控制器中使用外部私有服务时,我有一个问题,什么是更好的方法:

例如,我有一个私有的 jwt 服务管理器;我不能直接在我的控制器中调用这个服务,因为我有这个错误:

The "lexik_jwt_authentication.jwt_manager" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead."
Run Code Online (Sandbox Code Playgroud)

解决方案1:

我创建了一个这样的公共 JWTService:

<?php
namespace App\Service\JWT;

use FOS\UserBundle\Model\UserInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;

/**
 * Class JwtService
 * @package App\Service\JWT
 */
class JwtService
{
    /**
     * @var $JwtManager
     */
    private $JwtManager;

    public function __construct(JWTTokenManagerInterface $JwtManager)
    {
        $this->JwtManager = $JwtManager;
    }

    /**
     * @param UserInterface $user
     * @return string
     */
    public function create(UserInterface $user)
    {
        return $this->JwtManager->create($user);
    }
} 
Run Code Online (Sandbox Code Playgroud)

在我的控制器中调用这个类

解决方案2:

我在我的控制器服务中注入了“lexik_jwt_authentication.jwt_manager”,我通过构造函数使用了这个服务:

services:
   app.controller.user:
       class: AppBundle\Controller\UserController
        arguments:
            - '@lexik_jwt_authentication.jwt_manager'
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我像这样使用这项服务

class UserController extends Controller {

  private $jwt;

  public function __construct(JWTTokenManagerInterface $jwt) {
    $this->jwt = $jwt;
  }

  public function myAction() {
    // $this->jwt->...
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Jor*_*rge 3

注射(2 个选项)。自动装配会处理它。尽可能避免接触容器。