Answer the question
In order to leave comments, you need to log in
Why would a normal project need to use __invoke?
I read the answer to a similar question: https://qna.habr.com/q/626234 - but as for me, these are not answers at all, because they answer the question "How?", but do not answer the question " What for?"
I used to have this question before, but now it came up again when I was picking Laravel Sanctum :) Guard is called there via __invoke
And what's the point? Is it possible to do everything without __invoke?
Why use an extra entity if you can not use it?
I want to understand, because - what if it's somehow convenient? :-)
Answer the question
In order to leave comments, you need to log in
__invoke()
method allows you to turn an object into a function that we can pass / receive / resolve through the callable pseudo-type.
A sort of element of functional programming.
Well suited where we build a pipe or reduce, for which the FP approach is the most expressive and concise. I am not familiar with the Laravel architecture, but I can assume that some pipeline is drawn for authorization, where you can execute different pipes or filters for verification / validation or something with this approach, and this is more concise ...
Example:
public function add(callable $pipe) {
//..
}
...
$pipeline = (new Pipeline)
->add(fn() => true)
->add(fn(bool $enabled) =>'Maks enabled')
->add(new MaksHandler()) // тут класс с методом __invoke и работает как анонимка
;
Reply from Vitsliputsli
It’s right that they didn’t understand, because. no one answered you.
Quite right, you can just specify a method where the type is callable, and there is no difference.
Or, as Lentyuy wrote above, just call the class method, and its need to be described in the interface without any callable at all.
If you use OOP, then you don't need invoke, operate on objects, not functions, and not object-as-function mutants.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question