Skip to content

Instantly share code, notes, and snippets.

@samirmhsnv
Last active June 26, 2022 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samirmhsnv/2a6420baf9f06a98443f09b7eb41b303 to your computer and use it in GitHub Desktop.
Save samirmhsnv/2a6420baf9f06a98443f09b7eb41b303 to your computer and use it in GitHub Desktop.
Laravel Routing withController only - Using PHP 8 Attributes on Laravel Routing
<?php
namespace App\Providers;
use App\Attributes\Route as RouteAttribute;
class RouteServiceProvider extends ServiceProvider
{
// ...
public function boot()
{
$this->routes(function () {
$rii = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(app_path('Http/Controllers')));
foreach ($rii as $file) {
// pass if the directory
if ($file->isDir()) continue;
// make our controller namespace
$class = 'App\\Http\\Controllers\\' . $file->getBasename('.php');
// create our virtual class
$reflectionClass = new \ReflectionClass($class);
// collect attributes of class if the invokable method is defined
$classAttributes = collect($reflectionClass->getAttributes(RouteAttribute::class));
// check if the class have attribute itself
if ($classAttributes->isNotEmpty()) {
$arguments = collect($classAttributes->first()->getArguments());
// register our dynamic route
Route::match($arguments->get('method'), $arguments->get('path'), $class)
->middleware($arguments->get('middlewares', []));
}
// check each method individually
foreach ($reflectionClass->getMethods() as $method) {
// collect all attributes of the method
$methodAttributes = collect($method->getAttributes(RouteAttribute::class));
// pass if the method doesn't have any defined attributes
if ($methodAttributes->isEmpty()) continue;
// get arguments of our defined attribute
$arguments = collect($methodAttributes->first()->getArguments());
// register our dynamic route
Route::match($arguments->get('method'), $arguments->get('path'), $class . '@' . $method->getName())
->middleware($arguments->get('middlewares', []));
}
}
});
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment