DEV Community

Cover image for Slim Php Framework: How to create Route Wrapper Class in Slim?
Asif Sheikh
Asif Sheikh

Posted on

Slim Php Framework: How to create Route Wrapper Class in Slim?

Hello everyone!✌

Now we are going to discuss about creating Route Wrapper Class in Slim Php Framework.

We have to follow few steps to creating route class and I hope you to enjoy it. It makes life easier for slim developer.

STEP 1: Creating Route Wrapper Class

Creating a new php file in App\Core\Route.php in your slim project directory. I have named Route.php.

<?php

namespace App;

use Slim\App;

class Router
{
    protected $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function get($pattern, $callable)
    {
        $this->app->get($pattern, $callable);
    }

    public function post($pattern, $callable)
    {
        $this->app->post($pattern, $callable);
    }

    public function put($pattern, $callable)
    {
        $this->app->put($pattern, $callable);
    }

    public function delete($pattern, $callable)
    {
        $this->app->delete($pattern, $callable);
    }

    public function patch($pattern, $callable)
    {
        $this->app->patch($pattern, $callable);
    }

    public function group($pattern, $callable)
    {
        $this->app->group($pattern, $callable);
    }

    public function middleware($middleware)
    {
        $this->app->add($middleware);
    }

    public function controller($pattern, $controller)
    {
        $this->app->any($pattern . '[/{action}]', function ($request, $response, $args) use ($controller) {
            $action = $args['action'] ?? 'index';
            $controllerInstance = new $controller();
            return $controllerInstance->$action($request, $response, $args);
        });
    }

    public function resource($pattern, $controller)
    {
        $this->app->get($pattern, $controller . ':index');
        $this->app->get($pattern . '/create', $controller . ':create');
        $this->app->post($pattern, $controller . ':store');
        $this->app->get($pattern . '/{id}', $controller . ':show');
        $this->app->get($pattern . '/{id}/edit', $controller . ':edit');
        $this->app->put($pattern . '/{id}', $controller . ':update');
        $this->app->delete($pattern . '/{id}', $controller . ':destroy');
    }
}
Enter fullscreen mode Exit fullscreen mode

STEP 2: Use Above Route Class in index.php

<?php

use Slim\Factory\AppFactory;
use App\Router;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

$router = new Router($app);

// Define your routes
$router->get('/home', function ($request, $response, $args) {
    $response->getBody()->write('Hello, Home!');
    return $response;
});

$router->post('/submit', function ($request, $response, $args) {
    // handle post request
    return $response;
});

// Grouped routes
$router->group('/api', function () use ($router) {
    $router->get('/users', function ($request, $response, $args) {
        $response->getBody()->write('List of users');
        return $response;
    });

    $router->post('/users', function ($request, $response, $args) {
        // handle post request
        return $response;
    });
});

// Controller route
$router->controller('/product', \App\Controllers\ProductController::class);

// Resource route
$router->resource('/articles', \App\Controllers\ArticleController::class);

$app->run();
Enter fullscreen mode Exit fullscreen mode

Thanks for giving your time and considerations!✨

Top comments (2)

Collapse
 
xwero profile image
david duymelinck

Because the router is a part of the App class you could extend that, instead of creating Router class where you need to add all the router functionality.

src/MyAppFactory.php

<?php

namespace App;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Slim\Factory\AppFactory;
use Slim\Interfaces\CallableResolverInterface;
use Slim\Interfaces\MiddlewareDispatcherInterface;
use Slim\Interfaces\RouteCollectorInterface;
use Slim\Interfaces\RouteResolverInterface;

class MyAppFactory extends AppFactory
{
    public static function create(?ResponseFactoryInterface $responseFactory = null, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null, ?RouteCollectorInterface $routeCollector = null, ?RouteResolverInterface $routeResolver = null, ?MiddlewareDispatcherInterface $middlewareDispatcher = null): MyApp
    {
        static::$responseFactory = $responseFactory ?? static::$responseFactory;
        return new MyApp(
            self::determineResponseFactory(),
            $container ?? static::$container,
            $callableResolver ?? static::$callableResolver,
            $routeCollector ?? static::$routeCollector,
            $routeResolver ?? static::$routeResolver,
            $middlewareDispatcher ?? static::$middlewareDispatcher
        );
    }

}
Enter fullscreen mode Exit fullscreen mode

src/MyApp.php

<?php

namespace App;

use Slim\App;

class MyApp extends App
{
    public function controller($pattern, $controller)
    {
        $this->any($pattern . '[/{action}]', function ($request, $response, $args) use ($controller) {
            $action = $args['action'] ?? 'index';
            $controllerInstance = new $controller();
            return $controllerInstance->$action($request, $response, $args);
        });
    }

    public function resource($pattern, $controller)
    {
        $this->get($pattern, $controller . ':index');
        $this->get($pattern . '/create', $controller . ':create');
        $this->post($pattern, $controller . ':store');
        $this->get($pattern . '/{id}', $controller . ':show');
        $this->get($pattern . '/{id}/edit', $controller . ':edit');
        $this->put($pattern . '/{id}', $controller . ':update');
        $this->delete($pattern . '/{id}', $controller . ':destroy');
    }
}
Enter fullscreen mode Exit fullscreen mode

public/index.php

use App\MyAppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = MyAppFactory::create();

$app->resource('/articles', \App\Controllers\ArticleController::class);

$app->run();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
asif_sheikh_d7d74ce8b9c9d profile image
Asif Sheikh

😊👍