Access currently logged in user in UserRepository in Sylius

醉酒当歌 提交于 2021-02-08 07:01:29

问题


I would like to do something like this.

sylius_backend_user_index:
    pattern: /
    methods: [GET]
    defaults:
        _controller: sylius.controller.user:indexAction
        _sylius:
            template: SyliusWebBundle:Backend/User:index.html.twig
            method: createFilterPaginator
            arguments: [$criteria, $sorting, $deleted, @service_container]

I would like to access service_container in createFilterPaginator method. Can any one help me to sort out this issue?


回答1:


First of all, no need for the whole service container, you need only security.context. I assume you have already extended the UserRepository so you can overwrite the createFilterPaginator() method and it is correctly configured as the sylius.repository.user service.

You have to add a simple setter to your respository:

class UserRepository extends BaseUserRepository
{
    protected $user;

    public setUserViaSecurityContext(SecurityContextInterface $securityContext)
    {
        $this->user = $securityContext->getToken()->getUser();
    }
}

Now you have to manipulate the service definition in a compiler pass

namespace Acme\Bundle\YourBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class ModifyRepositoryPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $container
            ->findDefinition('sylius.repository.user')
            ->addMethodCall('setUserViaSecurityContext', array(
                new Reference('security.context'),
            ))
        ;
    }
}

And call this Compiler pass in your bundles file:

namespace Acme\Bundle\YourBundle;

use Acme\Bundle\YourBundle\DependencyInjection\Compiler\ModifyRepositoryPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class AcmeYourBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new ModifyRepositoryPass());
    }
}


来源:https://stackoverflow.com/questions/24012947/access-currently-logged-in-user-in-userrepository-in-sylius

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!