Gonza
Gonza

Reputation: 360

Symfony 2 : Set a parameter globally based on Request

I will try to be very specific here.

Im using BazingaGeocoderBundle Integration of the Geocoder-php library into Symfony2. On the config.yml you can set the geolocation Providers with their params

config.yml

bazinga_geocoder:
    providers:
        google_maps:
            locale: en
            region: US

Also i have a service listener, used to know which api should i use based on domain name. If someone access i will access the specific api url

www.domain.us -> api.en.anotherdomain.com
www.domain.it -> api.it.anotherimaginarydomain.com

The service listener is setted on config.yml

services:
    kernel.listener.domain_listener:
        class: MyOwn\Bundle\WebBundle\Listener\DomainListener
        arguments:
        - %tld_allowed%
        tags:
        - { name: kernel.event_listener, event: kernel.request, method: onDomainGet }

On everyrequest i set a session value with the corresponding api domain.

I want to be able to specify the bazinga_geocoder params, so i can set the google_maps provider parameters (locale, region) based on the domain accessed.

How can i do that? im on the wrong path?

Upvotes: 2

Views: 898

Answers (1)

gremo
gremo

Reputation: 48899

I don't know how this bundle works, but looking at the code:

  • When a new provider is found (through the configuration), the extension will create a new Definition with id bazinga_geocoder.provider.$name
  • The definition is going to have a tag bazinga_geocoder.provider and a private visibility
  • The compiler pass will look for services tagged as bazinga_geocoder.provider and calls registerProvider on bazinga_geocoder.geocoder service, that is the Geocoder.

Maybe this may work: inject the bazinga_geocoder.provider.google_maps service in your request listener, then call $provider->setLocale($locale). I don't know hot to set the region, as there isn't a setter in the AbstractProvider class (neither in GoogleMapsProvider).

A "brutal" solution would be creating a new GoogleMapsProvider instance in the request listener, adding it to the geocoder. The listener should accept these services:

  • bazinga_geocoder.geocoder.adapter
  • bazinga_geocoder.geocoder

That is:

use Geocoder\Geocoder;
use Geocoder\Provider\GoogleMapsProvider;
use Geocoder\HttpAdapter\HttpAdapterInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class RequestListener
{
    private $adapter;
    private $geo;

    public function __construct(HttpAdapterInterface $adapter, Geocoder $geo)
    {
        $this->adapter = $adapter;
        $this->geo = $geo;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        // Get locale and region in some way

        // Create and register the provider, dynamically
        $provider = new GoogleMapsProvider($this->adapter, $locale, $region);
        $this->geo->registerProvider($provider);
    }
}

Upvotes: 3

Related Questions