Symfony2基于子域设置全局参数

时间:2016-01-04 10:12:36

标签: php symfony subdomain

使用symfony 2.8,我正在使用子域,我想根据子域显示不同的(让我们说)主页,我将子域存储在Domain表中,其中包含一个名为{{1的列}}。理想情况下,当用户访问subdomain时,我想在数据库中搜索“sub”并获取sub.example.com的{​​{1}}并将其设置为该特定的全局参数 domain,这样我就可以加载网站设置并从数据库加载其他动态数据(使用domain_id作为密钥)

这是我认为是正确的,如果有更好的方法来处理同样的问题,请告诉我,我可能会得到一个朋友,如果它对我来说是新的奖励。

2 个答案:

答案 0 :(得分:0)

我建议你听一下kernel.controller事件。确保您的侦听器具有容器感知功能,以便您可以通过执行$this->container->setParameter('subdomain', $subdomain);

来设置参数

此时您只需要检查您设置的参数,例如在控制器操作中,以便根据当前子域返回不同的视图。

参考:

  1. Container aware dispatcher
  2. Symfony2 framework events

答案 1 :(得分:0)

使用YAML配置而不是数据库来查看我的实现:https://github.com/fourlabsldn/HostsBundle。你或许可以获得一些灵感。

<?php
namespace FourLabs\HostsBundle\Service;

use Symfony\Component\HttpFoundation\RequestStack;
use FourLabs\HostsBundle\Model\DomainRepository;
use FourLabs\HostsBundle\Exception\NotConfiguredException;

abstract class AbstractProvider
{
    /**
     * @var RequestStack
     */
    protected $requestStack;

    /**
     * @var DomainRepository
     */
    protected $domainRepository;

    /**
     * @var boolean
     */
    protected $requestActive;

    public function __construct(RequestStack $requestStack, DomainRepository $domainRepository, $requestActive)
    {
        $this->requestStack = $requestStack;
        $this->domainRepository = $domainRepository;
        $this->requestActive = $requestActive;
    }

    protected function getDomainConfig()
    {
        $request = $this->requestStack->getCurrentRequest();

        if(is_null($request) || !$this->requestActive) {
            return;
        }

        $host = parse_url($request->getUri())['host'];

        if(!($domain = $this->domainRepository->findByHost($host))) {
            throw new NotConfiguredException('Domain configuration for '.$host.' missing');
        }

        return $domain;
    }
}

和听众

<?php

namespace FourLabs\HostsBundle\EventListener;

use FourLabs\HostsBundle\Service\LocaleProvider;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class LocaleListener
{
    /**
     * @var LocaleProvider
     */
    private $localeProvider;

    public function __construct(LocaleProvider $localeProvider) {
        $this->localeProvider = $localeProvider;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        if(HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }

        $event->getRequest()->setLocale($this->localeProvider->getLocale());
    }
}
相关问题