Symfony 2.6获取Service LoggedUser可捕获致命错误:参数3必须是一个实例

时间:2015-01-11 01:54:29

标签: symfony logging service dependency-injection

我想将security.token_storage实现为服务以获取登录的用户;所以当用户写一篇文章或评论字段时,#34;作者"自动设置。

我无法让它发挥作用:

尝试调用方法"得到"在班级" Blog \ BlogBu​​ndle \ Services \ PostManager"。

如何将其作为服务实施并使用?

UserManager(作为服务):     命名空间Usuarios \ UsersBundle \ Services;

class UserManager

public function getloggedUser()
{
    $loggedUser = $this->get('security.token_storage')->getToken()->getUser();

    return $loggedUser;
}

UserManager配置的service.yml:

services:
    user_manager:
        class: %user_manager.class%
        arguments:
            - @doctrine.orm.entity_manager

使用getloggedUser函数的PostManager:     命名空间Blog \ BlogBu​​ndle \ Services;

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;

public function createComment (Post $post, Request $request)
{
    $comment = new Comment();

    $comment->setPost($post);

    //this is the line failing:
    $comment->setAuthorName($this->um->getloggedUser());

    $form = $this->formFactory->create(new CommentType(), $comment);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $this->em->persist($comment);
        $this->em->flush();

        return true;
    }

    return $form;

注意" user_manager"被定义为服务并且功能齐全,因为使用它的其他功能正在运行。为什么我不能从PostManager服务调用UserManager服务?我得到的错误是:

Catchable Fatal Error: Argument 3 passed to Blog\BlogBundle\Services\PostManager::__construct() must be an instance of Usuarios\UsersBundle\Services\UserManager, none given, called in C:\xampp\htdocs\eScribely2\app\cache\dev\appDevDebugProjectContainer.php on line 2535 and defined 

1 个答案:

答案 0 :(得分:0)

服务没有控制器所做的get方法。您需要在构建服务时将容器作为参数传递,并将其存储为成员变量,然后调用您的服务。

$this->container->get('user_manager');

您可以选择传入您的用户经理,而不必使用容器。