Is it bad to use Reflection in production code?

I have a class Validatorthat instantiates a class Validationsthat contains all the validation methods. When a check is __callin progress, Validatorused to send a call to .Validator->validate_methodValidations->method

So, for example, there is a method in Validationscalled length_of. When the following code is executed:

$v = new Validator();
$v->validate_length_of(...);

checking length_ofin class Validations.

To ensure that it is __callnot trying to send an invalid or non-public method Validation, I use ReflectionMethodto verify the specified method:

$method = new ReflectionMethod($this->validations, $validation_method);
if (!$method->isPublic())
{
  // error
}

I'm sure this is the only way to determine if a method is public, but I'm not sure if Reflection is suitable for production code. Is that the smell of code?

+3
3

Reflection . is_callable ?

if (!is_callable(array('Validations', $validation_method)) {
    throw new LogicException('method does not exist');
}

, Validations $validation_method , . , , __call , Reflection .

+5

API Reflection , . , , . , , . , .

, , , Reflection. , . . .

__call ( ), class_implements, , , , Validator

public function __call($method, $args)
{
    if ( class_exists( $method )) {
        $validator = new $method;
        if($validator instanceof IValidate) {
            return call_user_func(array($validator, 'validate'), $args);
        }
        throw new BadMethodCallException('Class exists but is not a Validator');
    }
    throw new RuntimeException('Method does not exist');
}

: Zend Framework , . ZF , , ZF. PEAR .

+1

IMHO, I would deviate from using reflection in production code. Instead of trying to call validate_something, I would create an interface that has the required validation method. Then for each valiadtor class, you simply call $ valid-> validate (). It would be easier for an interpreter to cache this code.

0
source

Source: https://habr.com/ru/post/1769633/


All Articles