thinkphp controller scheduling usage example
- 2021-01-11 01:55:27
- OfStack
1. How to get the module name and controller name from the address bar parameter (even if there is routing and rewrite module open)
2. How does tp implement pre - and post-method function modules, and how to execute methods with parameters?
php system comes with ReflectionClass,ReflectionMethod class, can reflect user-defined class properties, method permissions and parameters and other information, through these information can accurately control the execution of the method
The main methods used by ReflectionClass:
hasMethod(string) whether a method exists
getMethod(string) method
ReflectionMethod main methods:
getNumberOfParameters() Gets the number of arguments
getParamters() gets parameter information
3. Code Demo
<?php
class IndexAction{
public function index(){
echo 'index'."\r\n";
}
public function test($year=2012,$month=2,$day=21){
echo $year.'--------'.$month.'-----------'.$day."\r\n";
}
public function _before_index(){
echo __FUNCTION__."\r\n";
}
public function _after_index(){
echo __FUNCTION__."\r\n";
}
}
// perform index methods
$method = new ReflectionMethod('IndexAction','index');
// Permission determination
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);
}
}
}
// Executes methods with arguments
$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!';