note 125836 added to reflectionclass.newinstancewithoutconstructor
| From: | ben at NOSPAM dot fanmade dot de | Date: | Wed, 17 Feb 2021 19:51:52 +0000 |
| Subject: | note 125836 added to reflectionclass.newinstancewithoutconstructor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219319@lists.php.net to get a copy of this message | ||
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
:)
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.245 (proxied: 95.223.183.77)
----
Manual Page -- http://php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php
Edit -- https://master.php.net/note/edit/125836
Del: integrated -- https://master.php.net/note/delete/125836/integrated
Del: useless -- https://master.php.net/note/delete/125836/useless
Del: bad code -- https://master.php.net/note/delete/125836/bad+code
Del: spam -- https://master.php.net/note/delete/125836/spam
Del: non-english -- https://master.php.net/note/delete/125836/non-english
Del: in docs -- https://master.php.net/note/delete/125836/in+docs
Del: other reasons-- https://master.php.net/note/delete/125836
Reject -- https://master.php.net/note/reject/125836
Search -- https://master.php.net/manage/user-notes.php