我是Symfony的新手, 我尝试使用依赖注入使用户进入服务(我认为)
services.yaml:
App\Service\Test\RESTAuthenticatedService:
calls:
- method: getTrigramme
arguments:
- '@security.token_storage'
在我的RESTAuthenticatedService.php中:
namespace App\Service\Test; .... class RESTAuthenticatedService extends AbstractController { protected $session; private $user; .... public function getTrigramme(){ $user = $this->token_storage->getToken()->getUser();
ERROR :
Notice: Undefined property: App\Service\Test\PrestataireService::$token_storage
能帮我吗?
好的,首先感谢大家,我尝试了您所说的内容,但出现了这个错误:
Too few arguments to function App\Service\Test\ClientService::__construct(), 0 passed in D:\www\Interface_SAT\src\Controller\RecherchePrestataires.php on line 60 and exactly 2 expected
在我的控制器RecherchePrestataires.php中,我有:
.....
public function rechercher(Request $request) {
....
$recherchePresta = new PrestataireService();
在文件类PrestataireService中,我只有:
class PrestataireService extends ClientService {
在ClientService中:
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ClientService extends RESTAuthenticatedService
{
public $user;
public function __construct(SessionInterface $session, TokenStorageInterface $tokenStorage)
{
parent::__construct($session, $tokenStorage);
$this->setSession($session);
}
在RESTAuthenticatedService中:我已经完成了:
public function __construct(SessionInterface $session, TokenStorageInterface $tokenStorage)
{
$this->token_storage = $tokenStorage;
对不起,但是我尝试了很多事情。
答案 0 :(得分:1)
看来您没有在类中创建构造函数。
您已经在services.yaml中定义了您的类具有依赖项,但是您并未对该依赖项做任何事情。您需要创建构造函数,并将依赖项作为参数添加,然后分配给局部变量。
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class RESTAuthenticatedService extends AbstractController
/**
* @var TokenStorageInterface
*/
private $token_storage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->token_storage = $tokenStorage;
}
}
然后,您将可以访问$ this-> token_storage。
编辑:更改您的services.yaml以将依赖关系注入构造函数中。
App\Service\Test\RESTAuthenticatedService:
class: App\Service\Test\RESTAuthenticatedService
arguments:
- '@security.token_storage'