Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created December 29, 2020 11:55
Show Gist options
  • Select an option

  • Save kobus1998/071a28790508fde8dd208706e6d4dc13 to your computer and use it in GitHub Desktop.

Select an option

Save kobus1998/071a28790508fde8dd208706e6d4dc13 to your computer and use it in GitHub Desktop.
php attributes example routes
<?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