auraphp / Aura.Di

Dependency Injection System
MIT License
349 stars 63 forks source link

Feature Request: Take the params from the constructor definition #193

Closed Ciantic closed 4 years ago

Ciantic commented 4 years ago

I'm used to .NET Core's injection mechanism, it doesn't have this seemingly useless step of redefining the parameters:

        // Register cache
        $di->set(CacheInterface::class, $di->lazy(...));

        // Register server
        $di->set(Server::class, $di->lazyNew(Server::class));
        $di->params[Server::class] = [ // <- **THIS SEEMS LIKE USELESS REPETITION**
            "cache" => $di->lazyGet(CacheInterface::class),
        ];

The Aura could infer the params[] array from the __constructor() definition:

class Server {
    public function __construct(CacheInterface $cache) {
        // ...
    }
    // ...
}

Is there a reason why we have to repeat the params during the service registration? The dependencies are laid bare in the constructor definition.

Ciantic commented 4 years ago

Apparently if I use auto-resolver I have to do it like this, though it has some extra boiler plate too:

        $builder = new ContainerBuilder();
        $di = $builder->newInstance(true);

        // Register cache
        $di->set(CacheInterface::class, $di->lazy(function () {
            return new Psr16Cache(new FilesystemAdapter());
        }));
        // Now the following line bothers me, why do I need this:
        $di->types[CacheInterface::class] = $di->lazyGet(CacheInterface::class);

        // Register server
        $di->set(Server::class, $di->lazyNew(Server::class));

Maybe I just inherit from DI and add a helper that always add a registered service to types.