gpslab / geoip2

A Symfony Bundle for the Maxmind GeoIP2 API
https://www.maxmind.com/
MIT License
54 stars 12 forks source link

How to use Service injection in Symfony 6 properly #87

Open TheAFOGroup opened 2 years ago

TheAFOGroup commented 2 years ago

Hi, thanks for the library!

I`m having quite some trouble understanding what the heck is going on. Basically, I want a service that I can use in Controllers and EventListeners.

After checking the issues here and comments, you mentioned to declare:

GeoIp2\Database\Reader:
        alias: 'geoip2.reader'
        public: true

However, this is not needed apparently. The moment you pass use GeoIp2\Database\Reader into the constructor, the following gets injected:

[ContainerLx2Tlzg\Reader_5400306 - GeoIp2\Database\Reader@proxy](http://.../_profiler/open?file=var\cache\dev\ContainerLx2Tlzg\Reader_5400306.php&line=7#line7) {#643 ▼
  -valueHolder16a63: null
  -initializer876c2: [Closure(&$wrappedInstance, LazyLoadingInterface $proxy)](http://.../_profiler/open?file=var\cache\dev\ContainerLx2Tlzg\**getGeoip2_Database_CityReaderService**.php&line=22#line22) {#647 ▼
    class: "[ContainerLx2Tlzg\getGeoip2_Database_CityReaderService](http://.../_profiler/open?file=var\cache\dev\ContainerLx2Tlzg\getGeoip2_Database_CityReaderService.php&line=11#line11)"
    use: {▼
      $container: ContainerLx2Tlzg\App_KernelDevDebugContainer {#55 …}
    }
  }

As above the City reader gets injected automatically, and I have no way of getting the ASN reader for example. I have also commented out default_database but without any effect.

So back to my question, how to use your library properly and as intended?

The requirement is quite simple:

Many thanks!

peter-gribanov commented 2 years ago

If you have several reader services, then Symfony dependency injector will not be able to automatically determine which one to inject, because for Symfony injector, these services are the same and only you know which one to use where. You will have to explicitly describe dependency injection in configs or use a ReaderFactory or create a proxy classes for each databases.