2

a service of my application needs to access a $_SERVER variable (which is provided by apache) called: $_SERVER['GEOIP_COUNTRY_CODE'];

What are good ways to achieve this?

My current guess would be to inject the RequestStack but on the other hand I dont want to couple the complete RequestStack to this service.

Are there other ways of achieving this?

P.S. Please don't answer me with links to bundles like https://github.com/aferrandini/Maxmind-GeoIp etc.

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
gries
  • 1,135
  • 6
  • 29

2 Answers2

5

You have to tell your service to inject the request stack to get current request.

You can call the request service but it is may cause a ScopeWideningInjectionException exception because the request can change.

Your service file:

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

YML:

services:
    your_great_service:
        class:     Some\GreatBundle\ServicePath\GreatService
        arguments: ["@request_stack"]
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
-2

If I understands you, you want to use a $_SERVER variable in a service. I found this in the Symfony documentation:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

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

As I can see, there is no problem to achieve your variable:

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

Requests and Responses in Symfony

vobence
  • 523
  • 2
  • 5