我已经安装了Symfony 4的最新版本,真是太难了!
但是当我们在您的 Controller 中使用外部私有(private)服务时,我有一个问题,哪种更好的方法是:
例如,我有一个jwt服务管理器,它是私有(private)的。我无法在我的 Controller 中直接调用此服务,因为出现此错误:
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."
解决方案1:
我创建一个像这样的公共(public)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);
}
}
在我的 Controller 中调用此类
解决方案2:
我在 Controller 服务中注入(inject)了'lexik_jwt_authentication.jwt_manager',并通过构造函数使用了该服务:
services:
app.controller.user:
class: AppBundle\Controller\UserController
arguments:
- '@lexik_jwt_authentication.jwt_manager'
在我的 Controller 中,我像这样使用这项服务
class UserController extends Controller {
private $jwt;
public function __construct(JWTTokenManagerInterface $jwt) {
$this->jwt = $jwt;
}
public function myAction() {
// $this->jwt->...
}
}
预先感谢。
最佳答案
注入(inject)(2个选项)。自动布线将处理该问题。避免尽可能接近容器。
关于service - Symfony 4-带有私有(private)外部服务的最佳实践,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48682016/