php-school / php-workshop

🔮 PHP School workshop framework. The stuff you use to build your workshop!

Home Page:http://www.phpschool.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PHP-DI tip

mnapoli opened this issue · comments

Hi!

I was curious and had a look at the package ;) Just one thing I noticed in your config:

    Color::class => factory(function (ContainerInterface $c) {
        $colors = new Color;
        $colors->setForceStyle(true);
        return $colors;
    }),

You can remove factory(), if a definition is a closure then it's implicitly interpreted as a factory by PHP-DI:

    Color::class => function (ContainerInterface $c) {
        $colors = new Color;
        $colors->setForceStyle(true);
        return $colors;
    },

Also you can skip the $c parameter if you don't use it (it's not required). That's just a matter of preference of course.

That's all, feel free to close that issue once you read since it was just a comment!

Thanks for tip! will clean it up later today 😄

hey @mnapoli I updated a few things in the config. Something that stung me a little was invokable class factories. It seems when auto wiring is off, the invokable class will not be created. This makes sense I guess, it just took me a while to figure it out.

For example:

EventDispatcher::class => factory(EventDispatcherFactory::class),

Where EventDispatcherFactory is a class implementing __invoke.

With auto-wiring off, this yields the following error when grabbing EventDispatcher from the container:

PHP Fatal error:  Uncaught exception 'DI\Definition\Exception\DefinitionException' with message 'Entry "PhpSchool\PhpWorkshop\Event\EventDispatcher" cannot be resolved: factory "PhpSchool\PhpWorkshop\Factory\EventDispatcherFactory" is neither a callable nor a valid container entry'

If I change the definitions to include EventDispatcherFactory as an object (or enable auto-wiring) all is fine:

EventDispatcher::class => factory(EventDispatcherFactory::class),
EventDispatcherFactory::class => object(),

Again, it makes sense why it would work like that, just took me some debugging to figure and writing a test case for PHP-DI which worked fine and then I was like wth, then I realised I had auto-wiring off and it must be that.

It does seems to be mentioned in the docs:

as a factory can be any PHP callable, you can use invocable objects, too: DI\factory(InvocableFooFactory::class) (or alternatively: DI\factory('invocable_foo_factory'), if it's defined in the container)

So yeah - my fault and ignore this 😄

Ah good catch! I've opened PHP-DI/PHP-DI#423 to add a more explicit error message in that case, let me know if you think that would/would not be helpful. Cheers!

Looks great! Thank you!