legend3---laravel中获取控制器名称和方法名称 legend3---laravel中获取控制器名称和方法名称

一、总结

一句话总结:

Route::current()->getActionName();会有完整的当前控制器名和方法名
public static function getControllerAndFunction()
{
  $action = Route::current()->getActionName();
  list($class, $method) = explode('@', $action);
  $class = substr(strrchr($class,'\'),1);
  return ['controller' => $class, 'method' => $method];
}

1、list($class, $method) = explode('@', $action);中的list($class, $method)的作用是什么?

让list中的$class和$method分别对应explode出来的数组的两个元素

2、strrchr($class,'\')的作用是什么?

strrchr() 函数查找字符串在另一个字符串中最后一次出现的位置,并返回从该位置到字符串结尾的所有字符。
AppHttpControllersAdminMyController中查找返回的结果是:MyController

3、substr函数的作用是什么?

Return part of a string
echo substr('abcdef', 1);     // bcdef

二、laravel中获取控制器名称和方法名称

1、示例

legend3---laravel中获取控制器名称和方法名称
legend3---laravel中获取控制器名称和方法名称

2、控制器中调用代码:

class MyController extends Controller
{
    //修改密码的界面
    public function changePasswordForm(){
        dd(AppModelControllerAndFunction::getControllerAndFunction());
        return view('admin.my.change_pass');
    }

3、获取控制器名称和方法名称的代码

 1 <?php
 2 
 3 namespace AppModel;
 4 
 5 use IlluminateDatabaseEloquentModel;
 6 
 7 class ControllerAndFunction extends Model
 8 {
 9     //
10     /**
11      * @return array
12      * 获取控制器和方法名
13      */
14     public static function getControllerAndFunction()
15     {
16         $action = Route::current()->getActionName();
17         list($class, $method) = explode('@', $action);
18         $class = substr(strrchr($class,'\'),1);
19         return ['controller' => $class, 'method' => $method];
20     }
21 
22 
23     /**
24      * 将控制器和方法用点拼接
25      * @return string
26      */
27     public static function jointControllerAndFunction(){
28         $action = Route::current()->getActionName();
29         list($class, $method) = explode('@', $action);
30         $class = substr(strrchr($class,'\'),1);
31         return $class.'.'.$method;
32     }
33 
34 }
$action = Route::current()->getActionName();的结果为:

legend3---laravel中获取控制器名称和方法名称
legend3---laravel中获取控制器名称和方法名称

list($class, $method) = explode('@', $action);的结果为:

legend3---laravel中获取控制器名称和方法名称
legend3---laravel中获取控制器名称和方法名称

这一步得到方法名changePasswordForm

 $class = substr(strrchr($class,'\'),1);的结果为:

legend3---laravel中获取控制器名称和方法名称
legend3---laravel中获取控制器名称和方法名称

 这一步得到控制器名MyController

strrchr($class,'\')的结果为:

legend3---laravel中获取控制器名称和方法名称
legend3---laravel中获取控制器名称和方法名称

 所以还需要substr从1的位置开始截取才的到控制器名称myController

 4、相关补充

strrchr() 函数(在php中)查找strchr()函数,它查找字符串中首次出现指定字符以及其后面的字符。