我想设置一个服务来让用户登录。该服务在另一个使用用户名将其设置为评论作者的服务中使用。我遇到的问题是,由于 get 语句,我无法初始化 getloggedUSer 函数。 security.context 已在 Symfony2.6 中更新,我想按照此处的建议使用它 http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
我得到的错误:
Attempted to call method "get" on class "Usuarios\UsersBundle\Services\UserManager".
您的意思是调用“getloggedUser”吗?
包含我要使用的功能的 UserManager 服务:
namespace Usuarios\UsersBundle\Services;
/**
* Class UserManager
*/
class UserManager
{
private $em;
/**
* @param EntityManager $em
*
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* @return mixed
*/
public function getloggedUser()
{
###Failing Line
$loggedUser = $this->get('security.token_storage')->getToken()->getUser();
return $loggedUser;
}
调用 getloggedUser 函数的 PostManager 服务:
namespace Blog\BlogBundle\Services;
/**
* Class PostManager
*/
class PostManager
{
private $em;
private $formFactory;
private $um;
/**
* @param EntityManager $em
* @param formFactoryInterface $formFactory
* @param UserManager $um
*/
public function __construct(EntityManager $em, FormFactoryInterface $formFactory, UserManager $um)
{
$this->em = $em;
$this->formFactory = $formFactory;
$this->um = $um;
}
/**
* Create and validate a new comment
*
* @param Post $post
* @param Request $request
* @return FormInterface|boolean
*/
public function createComment (Post $post, Request $request)
{
$comment = new Comment();
$comment->setPost($post);
$comment->setAuthorName($this->um->getloggedUser());### Failing Line
$form = $this->formFactory->create(new CommentType(), $comment);
$form->handleRequest($request);
if ($form->isValid()) {
$this->em->persist($comment);
$this->em->flush();
return true;
}
return $form;
}
“get”显然在这种情况下不可用。 ### 符号在实际代码中不存在,仅供引用。我的代码声明有什么问题?
最佳答案
这是因为您的UserManager
服务定义错误。您无法在尝试时使用方法 get
- 这是从提供 get
方法的 Controller
类中获得的习惯。
您需要做的是更改 UserManager
服务的定义,以便将 TokenStorage
注入(inject)到您的类中。
services.yml
services:
your.user.manager.service:
class: Usuarios\UsersBundle\Services\UserManager
arguments: [@doctrine.orm.entity_manager, @security.token_storage]
用户管理器:
class UserManager
{
public function __construct(EntityManager $em, $tokenStorage)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public function getloggedUser()
{
$loggedUser = $this->tokenStorage->getToken()->getUser();
return $loggedUser;
}
}
关于symfony - 服务中的 Simfony2 服务尝试调用方法 "get",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27891771/