Last active
June 26, 2022 12:19
-
-
Save samirmhsnv/2a6420baf9f06a98443f09b7eb41b303 to your computer and use it in GitHub Desktop.
Laravel Routing withController only - Using PHP 8 Attributes on Laravel Routing
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 | |
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