如何将$ _SERVER变量注入服务

gri*_*ies 2 php geoip symfony

我的应用程序的服务需要访问一个名为的$_SERVER变量(由apache提供):$_SERVER['GEOIP_COUNTRY_CODE'];

有什么好方法可以达到这个目的?

我目前的猜测是注入RequestStack但另一方面我不想将完整的RequestStack耦合到这个服务.

还有其他方法可以实现这一目标吗?

PS请不要回复我的链接,如https://github.com/aferrandini/Maxmind-GeoIp等.

R. *_*kan 5

您必须告诉您的服务注入请求堆栈以获取当前请求.

您可以调用请求服务,但它可能会导致ScopeWideningInjectionException异常,因为请求可能会更改.

您的服务文件:

<?php

namespace Some\GreatBundle\ServicePath;
use Symfony\Component\HttpFoundation\RequestStack;

class GreatService
{
    private $request;

    public function __construct(RequestStack $requestStack)
    {
        $this->request = $requestStack->getCurrentRequest();
    }

    public function getGeoIpCountryCode()
    {
        return $this->request->server->get("GEOIP_COUNTRY_CODE");
    }
}
Run Code Online (Sandbox Code Playgroud)

阳明:

services:
    your_great_service:
        class:     Some\GreatBundle\ServicePath\GreatService
        arguments: ["@request_stack"]
Run Code Online (Sandbox Code Playgroud)