Skip to content

[11.x] Make Router Tappable - #52051

Merged
taylorotwell merged 1 commit into
laravel:11.xfrom
mabdullahsari:router-tappable
Jul 8, 2024
Merged

taylorotwell merged 1 commit into
laravel:11.xfrom
mabdullahsari:router-tappable

Conversation

@mabdullahsari

Copy link
Copy Markdown

Currently, I have a bunch of infrastructural packages that provide a dedicated route file. The entry point of said packages is the Http endpoint, and to account for maximum customizability, the routes do not get registered automatically in the corresponding ServiceProvider. Reasoning is simple: the Router component makes use of a powerful stacking context, allowing for terrific composability and customization. So, instead of trying to predict every single user-land use case out there, it made much more sense to provide a base RouteRegistrar for each package and let the user decide what they want to do with it eventually.

  • Want to host it on a subdomain? ✅
  • Want to add a route prefix? ✅
  • Want to add a route name prefix? ✅
  • Want to add something else ad infinitum? ✅

Basically, this is how things are done currently:

// routes/package.php
<?php declare(strict_types=1);

use Illuminate\Routing\Router;
use RedactedWebhooks\WebhookController;

/** @var Router $router */
$router->post('redacted', WebhookController::class)->name('redacted')

Then somewhere in the UI where all of the webhooks are composed:

<?php declare(strict_types=1);

require __DIR__ . '/../src/redacted1-webhooks/routes/webhooks.php';
require __DIR__ . '/../src/redacted2-webhooks/routes/webhooks.php';
require __DIR__ . '/../src/redacted3-webhooks/routes/webhooks.php';
require __DIR__ . '/../src/redacted4-webhooks/routes/webhooks.php';

In package tests:

protected function defineRoutes($router)
{
    require __DIR__ . '/../routes/webhooks.php';
}

Thanks to this single line of addition, we can now do:

class RouteRegistrar
{
    private const string ENDPOINT = 'redacted';

    public function __invoke(Router $router)
    {
        $router->post(self::ENDPOINT, WebhookController::class)->name(self::ENDPOINT);
    }
}

And in the UI:

$router
    ->tap(new Redacted1Webhooks\RouteRegistrar())
    ->tap(new Redacted2Webhooks\RouteRegistrar())
    ->tap(new Redacted3Webhooks\RouteRegistrar())
    ->tap(new Redacted4Webhooks\RouteRegistrar());

In tests:

protected function defineRoutes($router)
{
    $router->tap(new \RedactedWebhooks\RouteRegistrar());
}

Thanks!

@taylorotwell
taylorotwell merged commit 6df12d1 into laravel:11.x Jul 8, 2024
@mabdullahsari
mabdullahsari deleted the router-tappable branch July 8, 2024 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants