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.
Injection (2 option). Autowiring will handle it. Avoid access the container as much as possible.
Solution 3 :
public function myAction(JWTTokenManagerInterface $jwt) {
// $jwt->...
}
@Jorge do you thin it's a good pratice ?
Thx.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With