Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4 - Best Practice with private external service

I've install last version of Symfony 4 and it's rocks !

But i've got a question when we use external private service in your controller what is the better way :

For exemple i've got jwt service manager which is private; I can't call this service directly in my controller because i've got this error :

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."

Solution 1:

i create a public JWTService like this :

<?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);
    }
} 

To call this class in my controller

Solution 2 :

I inject 'lexik_jwt_authentication.jwt_manager' in my controller service and i use this service by constructor :

services:
   app.controller.user:
       class: AppBundle\Controller\UserController
        arguments:
            - '@lexik_jwt_authentication.jwt_manager'

And in my controller i use this service like this

class UserController extends Controller {

  private $jwt;

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

  public function myAction() {
    // $this->jwt->...
  }
}

Thanks by advance.

like image 451
psylo66 Avatar asked Feb 08 '18 09:02

psylo66


2 Answers

Injection (2 option). Autowiring will handle it. Avoid access the container as much as possible.

like image 103
Jorge Avatar answered Nov 10 '22 18:11

Jorge


Solution 3 :

    public function myAction(JWTTokenManagerInterface $jwt) {
    // $jwt->...   
}

@Jorge do you thin it's a good pratice ?

Thx.

like image 41
psylo66 Avatar answered Nov 10 '22 17:11

psylo66