Доступ к текущему зарегистрированному пользователю в UserRepository в Sylius

StackOverflow https://stackoverflow.com//questions/24012947

  •  21-12-2019
  •  | 
  •  

Вопрос

Я бы хотел сделать что-то подобное.

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]

Я хотел бы получить доступ к service_container в createFilterPaginator способ.Кто-нибудь может помочь мне разобраться в этом вопросе?

Это было полезно?

Решение

Прежде всего, нет необходимости в целом сервисном контейнере, вам нужен только security.context.Я предполагаю, что вы уже продлили срок действия UserRepository таким образом, вы можете перезаписать createFilterPaginator() метод, и он правильно настроен как sylius.repository.user Обслуживание.

Вы должны добавить простой сеттер в свой аккаунт:

class UserRepository extends BaseUserRepository
{
    protected $user;

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

Теперь вам нужно манипулировать определением сервиса на этапе компиляции

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'),
            ))
        ;
    }
}

И вызовите этот Компилятор pass в вашем файле bundles:

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());
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top