flightphp / core

An extensible micro-framework for PHP
https://docs.flightphp.com
MIT License
2.6k stars 407 forks source link

Inject Middleware constructor arguments using the DI Container #578

Closed fadrian06 closed 2 months ago

fadrian06 commented 2 months ago

When I use Middlewares as FQCN, Flight doesn't call the constructor, it calls directly the before() and after() methods, and always must be declared as static... Now that support for DI container is a reality, it will be great inject dependencies in Middlewares objects and invoke before(), after() as instance methods instead of static methods.

Before invoke the before() static method, try to create and object and if Flight can't do it, delegate the instantiation to a DI container, besides, allow to call before() and after() as instance methods as well.

fadrian06 commented 2 months ago

Here an example:


class MyMiddleware {
  function __construct(
    private MyDependency $dep
  ) {
    // current this will not be called
    // expected invoke before before() :v
  }

  function before() {
    // current not work because it's not static
  }

  function after() {
    // current not work because it's not static
  }
}

// ...

Flight::group(
  '/users',
  require 'users.routes.php', // I organize routes in files that returns Closures :v
  [MyMiddleware::class]
);
n0nag0n commented 2 months ago

I actually agree with this. I think that Middleware should run in the same way that controllers run. If you declare the object, use the object, but otherwise it will create the object with the container handler you have specified.

n0nag0n commented 2 months ago

https://github.com/flightphp/core/pull/585

n0nag0n commented 2 months ago

Part of v3.9.0 https://github.com/flightphp/core/releases/tag/v3.9.0