Skip to content

Lumen middleware to use Route parameters as objects (like Laravel does)

Notifications You must be signed in to change notification settings

SpinyMan/lumen-route-param-to-object-middleware

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lumen route param to object middleware

Lumen middleware to use Route parameters as objects (like Laravel does)

This is a route middleware.

Installation:

  1. composer require spinyman/lumen-route-param-to-object-middleware
  2. Register middleware in ./bootstrap/app.php:
    $app->routeMiddleware(
        [
            'param2object' => \SpinyMan\LumenRouteParamToObject\Middleware\RouteParamToObject::class,
        ]
    );
  3. Add it to any group route (ex.: RouteServiceProvider):
    $this->router->group(
        [
            'middleware' => 'param2object',
        ],
        static function (\Laravel\Lumen\Routing\Router $router) {
            // your code goes here
        }
    );

Examples

Eloquent:

//router
$this->router->group(
    [
        'middleware' => 'param2object',
    ],
    static function (\Laravel\Lumen\Routing\Router $router) {
        $this->router->get(
            '/books/{book}',
            'BookController@show'
        );
    }
)
class Book extends \Illuminate\Database\Eloquent\Model
{
    protected $table = 'books';
}
class BookController extends \Laravel\Lumen\Routing\Controller {
    public function show(\Laravel\Lumen\Http\Request $request, Book $book)
    {
        $bookId = $book->getKey();
        // your code goes here
    }
}

Simple class:

//router
$this->router->group(
    [
        'middleware' => 'param2object',
    ],
    static function (\Laravel\Lumen\Routing\Router $router) {
        $this->router->get(
            '/namer/{namer}',
            'NamerController@run'
        );
    }
)
// Namer class
class Namer
{
    private $name;
    
    public function __construct(string $name)
    {
        $this->name = $name;
    }
    
    public  function getName(): string
    {
        return ucfirst(
            strtolower($this->name)
        );
    }
} 
class NamerController extends \Laravel\Lumen\Routing\Controller
{
    public function run(\Laravel\Lumen\Http\Request $request, Namer $namer)
    {
        return $namer->getName();
    }
}

About

Lumen middleware to use Route parameters as objects (like Laravel does)

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages