Hi, Habr! Today I want to tell you about my crutch, which helped me not to dive into the jungle of PHP Reflection . After all, everyone writes crutches, just someone writes big, and someone less.
I actively use Laravel in my projects. For those who are not familiar with this framework, do not despair, because I will explain incomprehensible moments.
This time I wrote some extension of the validation rules:
Validator::extend('someRule', function ($attribute, $value, $parameters, $validator) { // some code... return $result; // boolean }, ':attribute is invalid');
And I needed to receive the list of all rules transferred to the validator. As it turned out, this simple at first glance task took me a little longer than I had planned. The property was private. And there were no getters for him in the class implementation. Of course, I did not change the class, because after the composer update this edit will immediately fly off.
It should be said that I have never used Reflection before, but I heard what it is used for. So, I started reading the documentation. Naturally, the code from the example did not start up the first time and it was necessary to search for more. And then I thought that the solution should be easier.
And I found a simple and elegant crutch. Still, it's better not to do that. Private properties are private, so as not to go there. But circumstances require, so ...
Validator::extend('someRule', function ($attribute, $value, $parameters, $validator) { // -. . // , (, ) $ninja = function() { // return $this->initialRules; }; $initialRules = $ninja->call($validator); // $newThis // some code return $result; }, ':attribute is invalid');
If someone else did not understand, I will explain: I created an anonymous function that returns some property. And then I just changed the context to the context of the validator (laravel passes an instance of this class). Ie, the closure now has access to this object from the inside and can access any private property and method.
All this beauty works, since PHP 5.4
This is actually all that I wanted to tell. Maybe it was already invented before me, but this idea came to my head myself, so I decided to share it. Suddenly, this decision will make life easier for someone.
Thanks for attention.
Source: https://habr.com/ru/post/333396/
All Articles