2014-06-06 39 views
2

我的应用程序的服务需要访问$_SERVER变量(是Apache提供)呼吁:$_SERVER['GEOIP_COUNTRY_CODE'];

有什么好的方法来实现这一目标?

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

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

P.S. 请不要使用像https://github.com/aferrandini/Maxmind-GeoIp等捆绑软件的链接回复我。

+0

哪种是你的服务文件? yml或xml? –

+0

我使用yaml作为文件格式。 – gries

回答

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"); 
    } 
} 

阳明:

services: 
    your_great_service: 
     class:  Some\GreatBundle\ServicePath\GreatService 
     arguments: ["@request_stack"] 
+0

也许从请求堆栈中分离服务与额外的地理IP服务类:) –

-2

如果我理解了您,您希望在服务中使用$_SERVER变量。我发现这个symfony的文档中:

use Symfony\Component\HttpFoundation\Request; 

$request = Request::createFromGlobals(); 

// retrieve SERVER variables 
$request->server->get('HTTP_HOST'); 

正如我所看到的,是没有问题的,实现你的变量:

$request->server->get('GEOIP_COUNTRY_CODE'); 

Requests and Responses in Symfony

+0

是的,但我问是否有替代方案,所以我不必将完整的RequestStack注入到服务中。 – gries

+0

当然,你也可以使用旧的$ _SERVER superglobal。 – vobence