Skip to content

Instantly share code, notes, and snippets.

@szabomikierno
Created August 10, 2017 00:40
Show Gist options
  • Select an option

  • Save szabomikierno/7c49576ca562d4e7627d3e9e07f0c651 to your computer and use it in GitHub Desktop.

Select an option

Save szabomikierno/7c49576ca562d4e7627d3e9e07f0c651 to your computer and use it in GitHub Desktop.
Extended Laravel Router to include custom routes
<?php
namespace App\Core\Routing;
use Illuminate\Routing\Router as LaravelRouter;
use App\Core\Routing\DisplayRegistrar;
use App\Core\Routing\ApiRegistrar;
use App\Core\Routing\PageRegistrar;
// Similar as Route::resource, I register 3 other route 'shortcuts'. Display, Api and Page.
// Page registers a single get route with a closure that just returns a view, used for
// pages that don't really need much data or controller, but it's still more elegant
// than having closures directly in the routes file
// Display registers 4 get routes for a resource and is being handled by a 'DisplayController'
// Each of the routes / methods return a view. Basically the 4 get routes from the Resource controller
// However Display contollers are used to display pages / views for a resource and not as API endpoints
// - all
// - edit
// - new
// - single
// Api registers 6 routes, similar as resource routes, but these are used ONLY as API endpoints
// - list
// - view
// - store
// - update
// - delete
// - validation
class Router extends LaravelRouter
{
public function display($name, $controller, array $options = [])
{
if ($this->container && $this->container->bound(DisplayRegistrar::class)) {
$registrar = $this->container->make(DisplayRegistrar::class);
} else {
$registrar = new DisplayRegistrar($this);
}
$registrar->register($name, $controller, $options);
}
public function api($name, $controller, array $options = [])
{
if ($this->container && $this->container->bound(ApiRegistrar::class)) {
$registrar = $this->container->make(ApiRegistrar::class);
} else {
$registrar = new ApiRegistrar($this);
}
$registrar->register($name, $controller, $options);
}
public function page($name, $view) {
if ($this->container && $this->container->bound(PageRegistrar::class)) {
$registrar = $this->container->make(PageRegistrar::class);
} else {
$registrar = new PageRegistrar($this);
}
return $registrar->register($name, $view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment