Closed TCB13 closed 5 years ago
I used to have something similar to this built in as one of the strategies but removed it for several reasons. Partly because reflection is slow.
To answer your question properly though, I'd ask for what reason you want to do this over constructor injection? If I understand your goal I may be able to point to a better solution.
@philipobenito I want this because most routes require different and specific dependencies. My custom strategy basically allows me to have those dependencies automatically injected in the methods / avoid having to resolve them manually from the container.
And then I've other cases where I do inject "shared" dependencies on the controller as you said.
Okay, so, if you wanna do that, the custom strategy is the way to go. However, I'd suggest a better option might be to split up your controllers more, better separation of concerns that way too.
What if to cache a router with already resolved types of parameters of controller methods? In any case, if the same parameters are passed to the constructor, they still need to be resolved. If I understand correctly, it takes exactly the same amount of time.
I want to pass dependencies to methods like Laravel.
cache a router with already resolved types of parameters of controller methods
How do you go about that?
My way to go about this (poorly described before to @philipobenito) is to pass generic stuff like a logger to the controller's constructor and some specific stuff to the route, for example, a route to create new Posts will have a new instance of the Post class injected to its method. And yes, this might be a dumb example becuse I could easy do $post = new Post;
but it explains my point.
Hello, I'm trying the router and it really is great, however I've a question about methods and dependency injection. I've created a Controller called
Single.php
as follows:And I can have a working router like:
I can also add the league container and have it resolve dependencies on my controller. For instance if
Single
now is:I can make sure the router injects an instance of
Test
in the constructor in this way:Now, I would like to be able to inject dependencies in my controller methods, example at
Single
add aAnotherDependency $dependency
parameter to thejsonArrayParameter
method:After reading the documentation I managed to do this by created a custom strategy that extends
JsonStrategy
replacing theinvokeRouteCallable
method like this:This solution works, however, is there a better way to do it? Can I use the container directly for this without modifying JsonStrategy or other strategies? Should I even do it at all?
Thank you.