Home > Article > Backend Development > thinkphp controller scheduling usage example_PHP tutorial
1. How to get the module name and controller name through the address bar parameters (even when there is routing and the rewrite module is turned on)
2.tp How to implement pre- and post-method function modules, and how to execute methods with parameters?
The ReflectionClass and ReflectionMethod classes that come with the PHP system can reflect information such as attributes of user-defined classes, method permissions and parameters, etc. Through this information, the execution of methods can be accurately controlled
The main methods used by ReflectionClass:
hasMethod(string) Whether there is a method
getMethod(string) Get the method
ReflectionMethod main method:
getNumberOfParameters() Get the number of parameters
getParamters() Get parameter information
3. Code demonstration
//Execute the index method
$method = new ReflectionMethod('IndexAction','index');
//Perform permission judgment
if($method->isPublic()){
$class = new ReflectionClass('IndexAction');
//Execute the pre-method
if($class->hasMethod('_before_index')){
$beforeMethod = $class-> ;getMethod('_before_index');
if($beforeMethod->isPublic()){
$beforeMethod->invoke(new IndexAction);
}
}
$method->invoke(new IndexAction);
//Execute the post method
if($class->hasMethod('_after_index')){
$beforeMethod = $class->getMethod('_after_index');
if( $beforeMethod->isPublic()){
$beforeMethod->invoke(new IndexAction);
}
}
}
//Execute the method with parameters
$method = new ReflectionMethod('IndexAction','test');
$params = $method->getParameters();
foreach ($params as $param ){
$paramName = $param->getName();
if(isset($_REQUEST[$paramName]))
$args[] = $_REQUEST[$ paramName];
elseif($param->isDefaultValueAvailable())
$args[] = $param->getDefaultValue();
}
if(count($args)== $method->getNumberOfParameters())
$method->invokeArgs(new IndexAction,$args);
else
echo 'parameters is not match!';