在 Sylius 的 UserRepository 中访问当前登录的用户 [英] Access currently logged in user in UserRepository in Sylius

查看:27
本文介绍了在 Sylius 的 UserRepository 中访问当前登录的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情.

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]

我想在 createFilterPaginator 方法中访问 service_container.有人能帮我解决这个问题吗?

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

推荐答案

首先,不需要整个服务容器,你只需要security.context.我假设您已经扩展了 UserRepository 以便您可以覆盖 createFilterPaginator() 方法并且它被正确配置为 sylius.repository.user服务.

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.

您必须向存储库添加一个简单的 setter:

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());
    }
}

这篇关于在 Sylius 的 UserRepository 中访问当前登录的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆