How to inject $_SERVER variable into a Service

强颜欢笑 提交于 2019-12-12 20:01:11

问题


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.


回答1:


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"]



回答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



来源:https://stackoverflow.com/questions/24076561/how-to-inject-server-variable-into-a-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!