Symfony:当用户拥有x角色时装饰服务

时间:2017-05-15 17:52:06

标签: php symfony symfony-2.7

我一直在寻找这个问题的答案,但我似乎无法在任何地方找到它。

我目前已经定义了装饰翻译服务的装饰器服务。但是,我只想在用户具有特定角色时修饰翻译服务。

services.yml

services:
    app.my_translator_decorator:
        class: MyBundle\MyTranslatorDecorator
        decorates: translator
        arguments: ['@app.my_translator_decorator.inner']
        public:    false

MyTranslatorDecorator.php

class MyTranslatorDecorator {

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    // more code...

}

1 个答案:

答案 0 :(得分:4)

容器在运行时之前被“编译”。你不能根据上下文来装饰服务,它总会被装饰。

但是,在装饰器中,如果没有必要,可以添加一个guard子句来不执行自定义代码。

服务定义:

services:
    app.my_translator_decorator:
        class:     AppBundle\MyTranslatorDecorator
        decorates: translator
        arguments: ['@app.my_translator_decorator.inner', '@security.authorization_checker']
        public:    false

装饰:

<?php

namespace AppBundle;

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Translation\TranslatorInterface;

class MyTranslatorDecorator implements TranslatorInterface
{
    private $translator;
    private $authorizationChecker;

    public function __construct(TranslatorInterface $translator, AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->translator = $translator;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function trans($id, array $parameters = [], $domain = null, $locale = null)
    {
        if (!$this->authorizationChecker->isGranted('ROLE_ADMIN')) {
            return $this->translator->trans($id, $parameters, $domain, $locale);
        }

        // return custom translation here
    }

    // implement other methods
}