capsulephp / di

Capsule DI container
MIT License
28 stars 3 forks source link

Autowiring factory arguments #7

Open SpareParts opened 2 years ago

SpareParts commented 2 years ago

Currently the only kind of factory autowiring Capsule supports is to always inject full Container object.

$def->{Foo::CLASS}
    ->factory(function (Container $container) {
        return new Foo(new Bar(), 'irk');
    });

I'm proposing using autowiring for factory callables as well. Analyze arguments and try to autowire them, use some kind of fluent syntax to provide values for arguments that can't be autowired (in the same/similar way we already do for classes).

$def->{Foo::CLASS}
    ->factory(function (BarFactory $factory, int $value) {
        return $factory->createWithValue($value);
    })
    ->argument('value', $def->get('bar_value');
pmjones commented 2 years ago

Thanks for this suggestion!

To help my research, can you point out where other containers are doing something similar?

SpareParts commented 2 years ago

Sure! php-di has DI\factory() helper function that autowires the callable and allows to specify arguments that can't be autowired. Specifically this part:

return [
    'Database' => DI\factory(function ($host) {...})
        ->parameter('host', DI\get('db.host')),
];