dimanche 17 octobre 2021

How to get method name from PHP 8 attribute (reflection)

I'm working on small PHP framework (for learning). It has a file with LoginController class containing a method with Route attribute (code below). Is there any way to get the name of the method in the Route attribute class using Reflection?

Class with method using attribute:

class LoginController {
    #[Route('GET', '/login')]
    public function index() {
        // some code
    }
}

"Route" attribute class:

use Attribute;
use ReflectionMethod;

#[Attribute]
class Route {
    public function __construct($method, $routeUri) {
        // Can I get the method name ("index") from attribute instead of writing it?
        // And the class name?
        $reflection = new ReflectionMethod(\App\Controllers\LoginController::class, 'index');
        $closure = $reflection->getClosure();

        // Register a route...
        Router::add($method, $routeUri, $closure);
    }
}




Aucun commentaire:

Enregistrer un commentaire