Found an example
there is a thing in laravel called FormRequest
.
Sometimes, I need extra validation. So I need to use some service there somehow. What options I have
- facade
- service locator via app() global function
- I also have instance of container there via
$this->container
which one is the best here? I suppose instance of container
I can't do constructor injection. Why? Because for me, it seams that there are too many arguments on the __construct
method
it look like this
Am I wrong with this one?
Also they (FormRequest
s) help me to make controllers slim.
I get all the extra data there (for example get user by email,
I mean not the current session user, but the one that I, for example, edit)
so I don't need to do this in other place.
what I also can do is to make some separate method, name it, for example, afterValidationRequestDataSetter
,
on the form request, call it at the end of all operations like
$this->container->call([$this, 'afterValidationRequestDataSetter'])
and it will inject all the dependencies that I need
(I suppose, have not tested yet), but that
-
is not constructor injection
-
looks a bit like a magic since you can't do search on who calls this method (especially, it will be hard for new people on the project)
what is your ides about that?
p.s. not laravel zombie-fan and not forcing people to use facades
@vladyslavstartsev just to confirm I understand the problem: you want to extract a complex validation rule out of the Form Request, correct?
Laravel real time Facades are GREAT for the use-case you described. They are straight-forward and easy to mentally parse when reading somebody else's code. Any developer with basic understand of Laravel will know your typed Form Request Object will run it's
rules
method and Facades will allow you to run a process with a single line while offering DI, automatic object instantiation and mockery.That being said, Laravel is smart enough to know that some people will cry a river over the wonders that Facades brings and for the Form Request case that was resolved by offering automatic resolution at the
rules
method. You can simply type-hint your dependency as an argument of therules
method and your object will be injected for your. It works almost the same way as Facades, except that it's a typed argument instead. Combined withRule
object, you can do wonders.Then define your rule object