PHP 8.5.0 Alpha 4 available for testing

Voting

: zero plus five?
(Example: nine)

The Note You're Voting On

ben at NOSPAM dot fanmade dot de
4 years ago
Such a function should definitely end up in productive code as rarely as possible.
There are always exceptions though :)
We have UseCase classes in our library extending an abstract UseCase having a constructor that does some setting up and it will even throw exceptions if some specific conditions are not yet met.
Within that UseCase the permissions are also defined.
Simplified example:
<?php
abstract class UseCase implements IUseCase
{
/** @var string[] */
protected array $requiredPermissions = [];

final public function
__construct(IPresenter $out)
{
// several startup checks, including authorization
}
}
?>
We already have a better solution, but it will take some time to refactor that and we will have to live with this for at least a few weeks.
Now I've had the idea to check the permissions in the application's incoming request way before the individual UseCase will be initialized.
So after seeing this method here I just introduced this little helper into our abstract UseCase:
<?php
public static function getRequiredPermissions(): array
{
$class = new ReflectionClass(get_called_class());

return
$class->newInstanceWithoutConstructor()->requiredPermissions;
}
?>
Now I'm able to check the permissions in my request without really touching anything in the library:
<?php
public function authorize(): bool
{
if (!
$this->user->hasPermissions(CreatePost::getRequiredPermissions())) {
return
false;
}
return
true;
}
?>
This does also have the benefit of adding one more reason to switch to our new UseCase classes ASAP :)

<< Back to user notes page

To Top