On my resource controllers I have the usual methods, index
store
update
etc.
I also have a construct
that manages middleware and authorization like so:
public function __construct()
{
$this->middleware('auth:sanctum')->only(['index', 'update', 'destroy']);
$this->authorizeResource(User::class, 'user');
}
On other occasions, such as in single method controllers I just use invoke
:
public function __invoke()
{
return new UserResource(auth()->user());
}
If I wanted to add middleware and an authroization policy, should I add it to the invoke
method or use a seperate construct
method as per my resource contoller detailed above?
CodePudding user response:
You can use __construct and __invoke methods simultaneously. I think you can use __construct method for that purpose.
CodePudding user response:
A constructor method is executed when a new object instance is created, i.e. when new Something()
is being called. In contrast, the __invoke()
magic method is called only when the code is trying to call an object as a function (see callbacks / the callable type).
<?php
class CanCallMe
{
public function __construct()
{
echo "Constructor executed.";
}
public function __invoke()
{
echo "Invoked.";
}
}
function call(callable $callback)
{
callback();
}
$callback = new CanCallMe(); // Constructor is executed here.
call(); // This is when the __invoke() method will be executed.