服务中的Symfony2服务尝试调用方法“get”

时间:2015-01-11 20:33:09

标签: symfony authentication service dependency-injection access-token

我想设置一个服务来让用户登录。此服务用于另一个使用用户名将其设置为注释作者的服务。我遇到的问题是,由于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”在这种情况下显然无法使用。 ###表示法不存在于实际代码中,仅供参考。我的代码声明有什么问题?

1 个答案:

答案 0 :(得分:2)

这是因为您的UserManager服务定义错误。您不能在尝试时使用方法get - 这是习惯于提供Controller方法的get类。

您需要做的是更改UserManager服务的定义,以便向您的班级注入TokenStorage

<强> services.yml

services:
    your.user.manager.service:
        class: Usuarios\UsersBundle\Services\UserManager
        arguments: [@doctrine.orm.entity_manager, @security.token_storage]

<强>的UserManager

class UserManager
{


    public function __construct(EntityManager $em, $tokenStorage)
    {
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
    }


    public function getloggedUser()
    {
        $loggedUser = $this->tokenStorage->getToken()->getUser();

        return $loggedUser;
    }
}