Home >PHP Framework >Laravel >laravel5 get controller method
In Laravel 5, getting the controller method is a very basic and commonly used operation. In some scenarios, we may need to get the name of the method executed by the current controller. So, how to get controller methods in Laravel 5? Next, let us find out together.
In Laravel 5, the $route object saves the routing information of the currently executing controller. This object contains the requested URI, request method, routing parameters, etc. If you want to get the method name of the current controller, you can get it through the "getActionName" method of the $route object.
/** 获取当前控制器方法名称 **/ public function getCurrentMethodName() { $route = Route::getCurrentRoute(); $action = $route->getActionName(); $fragments = explode('@', $action); $method = end($fragments); return $method; }
In the above code, we first obtain the current routing object through the Route::getCurrentRoute() method, and then use the "getActionName" method of the $route object to obtain the full path of the current controller method, such as " AppHttpControllersTestController@index". Next, we use the explode() function to intercept the method name part, and use the end() function to get the last element of the array, which is the method name of the controller. Finally, just return the method name.
In addition to using the $route object, we can also obtain controller methods through the PHP reflection mechanism. The PHP reflection mechanism provides a class ReflectionClass, which can be used to obtain class-related information, including methods, properties, constants, etc. Through ReflectionClass, we can get the method name of the current controller.
/** 获取当前控制器方法名称 **/ public function getCurrentMethodName() { $controller = Route::current()->getController(); $reflection = new ReflectionClass($controller); $method = $reflection->getMethod(Route::currentRouteAction()); return $method->name; }
In the above code, we first obtain the instance object of the current controller, and then use the ReflectionClass class to obtain the reflection information of the instance object. Next, obtain the currently executed method through the getMethod() method of the reflection instance. Finally, use the name attribute of the reflection method to get the method name and return it.
The above are the two methods of obtaining controller methods in Laravel 5. No matter which method is used, it will provide us with a very fast and convenient operation method, allowing us to better control the execution of the controller. If you have questions about Laravel 5 development or need to learn more about Laravel 5, please check out the official documentation or tutorials. Mastering Laravel 5 development capabilities will help you quickly gain an advantage in the field of web development.
The above is the detailed content of laravel5 get controller method. For more information, please follow other related articles on the PHP Chinese website!