使用自定义服务的编译器传递加载Symfony的参数

时间:2017-11-15 17:55:54

标签: php symfony parameters

根据这个问题How to load Symfony's config parameters from database (Doctrine)我有类似的问题。我需要动态设置参数,我想从另一个自定义服务提供数据。

所以,我有事件监听器,它设置当前帐户实体(通过子域或当前登录的用户)

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Doctrine\ORM\EntityManager;
use AppBundle\Manager\AccountManager;

use Palma\UserBundle\Entity\User;

/**
 * Class CurrentAccountListener
 *
 * @package AppBundle\EventListener
 */
class CurrentAccountListener {

    /**
     * @var TokenStorage
     */
    private $tokenStorage;

    /**
     * @var EntityManager
     */
    private $em;

    /**
     * @var AccountManager
     */
    private $accountManager;

    private $baseHost;

    public function __construct(TokenStorage $tokenStorage, EntityManager $em, AccountManager $accountManager, $baseHost) {
        $this->tokenStorage = $tokenStorage;
        $this->em = $em;
        $this->accountManager = $accountManager;
        $this->baseHost = $baseHost;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();

        $accountManager = $this->accountManager;
        $accountManager->setCurrentAccount( $this->getCurrentAccount($request) );
    }

    private function getCurrentAccount($request){
        if($this->getCurrentAccountByLoggedUser()) {
            return $this->getCurrentAccountByLoggedUser();
        }
        if($this->getCurrentAccountBySubDomain($request) ) {
            return $this->getCurrentAccountBySubDomain($request);
        }
        return;
    }

    private function getCurrentAccountBySubDomain($request) {
        $host = $request->getHost();
        $baseHost = $this->baseHost;

        $subdomain = str_replace('.'.$baseHost, '', $host);

        $account = $this->em->getRepository('AppBundle:Account')
                ->findOneBy([ 'urlName' => $subdomain ]);

        if(!$account) return;

        return $account;
    }

    private function getCurrentAccountByLoggedUser() {
        if( is_null($token = $this->tokenStorage->getToken()) ) return;

        $user = $token->getUser();
        return ($user instanceof User) ? $user->getAccount() : null;
    }

}

services.yml

app.eventlistener.current_account_listener:
    class: AppBundle\EventListener\CurrentAccountListener
    arguments:
        - "@security.token_storage"
        - "@doctrine.orm.default_entity_manager"
        - "@app.manager.account_manager"
        - "%base_host%"
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

非常简单的客户经理只有setter和getter。如果我需要访问当前帐户,请致电

$this->get('app.manager.account_manager')->getCurrentAccount();

一切正常。

现在我正在尝试使用编译器传递

从我的服务中设置一些参数
namespace AppBundle\DependencyInjection\Compiler;

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

class ParametersCompilerPass implements CompilerPassInterface {

    const ACCOUNT_MANAGER_SERVICE_ID = 'app.manager.account_manager';

    public function process(ContainerBuilder $container) {

        if(!$container->has(self::ACCOUNT_MANAGER_SERVICE_ID)) {
            return;
        }

        $currentAccount = $container->get(self::ACCOUNT_MANAGER_SERVICE_ID)
            ->getCurrentAccount();

        $container->setParameter(
            'current_account', $currentAccount
        );
    }

}

AppBundle.php

    namespace AppBundle;

    use AppBundle\DependencyInjection\Compiler\ParametersCompilerPass;
    use Symfony\Component\DependencyInjection\Compiler\PassConfig;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\HttpKernel\Bundle\Bundle;

    class AppBundle extends Bundle
    {
        public function build(ContainerBuilder $container)
        {
            parent::build($container);

            $container->addCompilerPass(new ParametersCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);
        }
}

无论我使用什么PassConfig,每次都将current_account设为 null 。有任何想法吗?

感谢您的关注。

1 个答案:

答案 0 :(得分:1)

首次运行Symfony时会执行编译传递(CLI命令或第一个http请求)。一旦缓存被构建(编译),这段代码就再也不会被执行了。

带参数的解决方案[我不建议这样做]

如果您的参数可以从一个HTTP请求更改为另一个HTTP请求,则不应使用参数,因为某些服务可能会在参数准备好之前初始化,而其他服务之后可能会初始化。虽然这是您想要的方式,但您可以添加一个侦听内核请求并在那里修改/设置参数的事件。看看https://symfony.com/doc/current/components/http_kernel.html#component-http-kernel-event-table

用户/会话中的当前帐户

如果currentAccount取决于记录的用户,为什么不将该信息存储在用户或会话中并从服务中访问它?