The one link that got my attention in this weeks The Weekly Drop was PHP Attributes Can Be Used for Route Definition and Discovery
As a long time user of Symfony this feels like Drupal is catching up, and I'm all for it. The Drupal developers are really embracing attributes. The first time I noticed it is when they started using it for hooks.
Next to the Route attribute the change also allows the use of invokable controllers. From the Drupal article:
namespace Drupal\router_test\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\Routing\Annotation\Route;
/**
* Test controller.
*/
#[Route(
'/test_class_attribute',
'test_class_attribute',
requirements: ['_access' => 'TRUE']
)]
class TestClassAttribute extends ControllerBase {
/**
* Provides test content.
*/
public function __invoke() {
return ['#markup' => 'Testing __invoke() with a Route attribute on the class'];
}
}
I see quite a few people using single route controllers. And to me it doesn't make sense having to name a method when PHP provides a way to invoke a class with a single public method.
With Symfony, Tempest and now Drupal offering attribute based routing, it looks like Laravel is the biggest framework that doesn't uses attributes for routing.
Laravel already has middleware attributes. This is one of the parts of the routing that is heavily used.
There is a third party package that makes it possible to use attributes for routing.
And you can use it with the Laravel middleware attributes.
This shows it could be a core feature.
It would be amazing when the frameworks could create a standard for the routing attributes. This would make it possible to use controllers in multiple PHP solutions with a few changes or a framework discovery feature.
What is your route attribute use? When you use a router config file, what is stopping you from using attributes?
Top comments (1)
lol, routing is just parsing the incoming url which is passed to PHP as a $_SERVER variable normally.
I've never understood why the frameworks make routing so damn complicated code-wise.
As a rule, anything you don't define should just 404.
And then you'd define the paths you want to process and what attributes each one accepts in the url.
Also which method(s) the path accepts. [CORS should let you do that, but of course it's site-wide instead]
That would completely eliminate bots trying to crawl server paths, [path traversal attacks would be useless]
but noooo everyone just wants to accept all requests and then somehow filter them to the particular things they want to render.
meh, just me being tired after working all day.
Have a good one.