FastRoute icon indicating copy to clipboard operation
FastRoute copied to clipboard

Consider callable factories for custom overrides?

Open pmjones opened this issue 1 year ago • 1 comments

Currently, the FastRoute class uses strings to indicate custom or override classes, then uses that string with a new call to create the override object. This means that the custom or override class cannot use an alternative constructor, which in turn limits additional or alternative functionality.

Allowing for the custom or override class to be specified as a string or callable, means that a callable can be invoked to return a fully-constructed object. This would let consumers add custom functionality to the custom or override class via a custom constructor. Cf. the as-yet-released CastRouteCollector which adds to the constructor parameters.

You could go further with this, and delegate object construction to a PSR-11 ContainerInterface, but that adds a dependency, and might over-complicate setup work.

pmjones avatar Mar 10 '24 18:03 pmjones

Thinking on this some more: enabling something more like "real" dependency injection might be preferable. As a proof-of-concept, see these three sequential PRs:

  • https://github.com/pmjones/FastRoute/pull/1 modifies RouteCollector to remove DataGenerator from the constrctor params, and make it a processRoutes() parameter instead. This makes the RouteCollector dependent only the RouteParser, at the cost of having to go over the added routes twice (once when adding, and again when processing).
  • https://github.com/pmjones/FastRoute/pull/2 gets rid of the Dispatcher and GenerateUri constructors entirely, meaning you can instantiate them via any DI container. Their new with() methods return a copy of the object after loading up the processed routes, meaning you don't need the processed data at instantiation time.
  • https://github.com/pmjones/FastRoute/pull/3 is the final piece, replacing the string constructor parameters and new instantiations inside FastRoute with the actual injected instances.

All tests pass, but I have not run the other QA tooling.

I understand that this rearrangement may not fit your vision for the project, so use/modify/discard as you see fit.

(p.s. I can see now that even RouteCollector might do well to get a with($routeParser) method, making it more like the other injectable objects.)

pmjones avatar Mar 12 '24 02:03 pmjones