Created
December 29, 2020 11:55
-
-
Save kobus1998/071a28790508fde8dd208706e6d4dc13 to your computer and use it in GitHub Desktop.
php attributes example routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| #[attribute] | |
| class Route | |
| { | |
| public $method; | |
| public $path; | |
| public function __construct($method, $path) { | |
| $this->method = $method; | |
| $this->path = $path; | |
| } | |
| } | |
| class Controller | |
| { | |
| // the attribute takes the parameters of the construct | |
| #[route('GET', '/user/:userId')] | |
| public function getUser($userId) | |
| { | |
| // do action | |
| } | |
| } | |
| // create reflection method | |
| $reflection = new ReflectionMethod(Controller::class, 'getUser'); | |
| // get all Route attributes | |
| $attribute = $reflection->getAttributes(Route::class); | |
| // initialises the class instance | |
| $route = reset($attribute)->newInstance(); | |
| // GET - /user/:userId | |
| echo $route->method . ' - ' . $route->path; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment