Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Last active March 27, 2021 03:21
Show Gist options
  • Save carloscarucce/fce40cb3299dd69957db001c21422b04 to your computer and use it in GitHub Desktop.
Save carloscarucce/fce40cb3299dd69957db001c21422b04 to your computer and use it in GitHub Desktop.
<?php
//PHP 8+
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Route
{
public function __construct(
public string $path,
public ?string $method = null,
public ?string $alias = null
)
{}
}
class Controller
{
#[Route('/index/')]
#[Route('/home/', alias: 'home')]
public function index()
{
echo 'index method call', "\r\n";
}
#[Route('/create/', 'POST')]
public function create()
{
echo 'create method call', "\r\n";
}
public function __construct()
{
echo 'new controller', "\r\n";
}
}
$reflectionClass = new ReflectionClass(Controller::class);
$methods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$reflectionMethod = new ReflectionMethod(Controller::class, $method->getName());
$attributes = $reflectionMethod->getAttributes(Route::class);
echo "reflecting method ",$method->getName(),"\r\n";
foreach ($attributes as $attribute) {
var_dump($attribute->newInstance());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment