PHP code example of njeaner / router

1. Go to this page and download the library: Download njeaner/router library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

njeaner / router example snippets


composer 

$router = new \Njeaner\Router\Router();

$container = new \NJContainer\Container\Container(); // or use any other container that implements \Psr\Container\ContainerInterface.
$router = new \Njeaner\Router\Router($container);

/** register get routes */
$router->get("/my-path", fn()=> "returned value when route callback is executed", "route_name");

/** register post routes */
$router->post("/my-path", fn()=> "returned value when route callback is executed", "route_name");

/** register put routes */
$router->put("/my-path", fn()=> "returned value when route callback is executed", "route_name");

/** register patch routes */
$router->patch("/my-path", fn()=> "returned value when route callback is executed", "route_name");

/** register delete routes */
$router->delete("/my-path", fn()=> "returned value when route callback is executed", "route_name");

/** register routes use any function that access \Njeaner\Router\RouteMethods enum as first argument */
$router->any(\Njeaner\Router\RouteMethods::get, "/my-path", fn()=> "returned value when route callback is executed", "route_name");

/** In the case below, route name is not defined. "my-path" will be use as route name */
$router->delete("/my-path", fn()=> "returned value when route callback is executed");

$router
    ->get("/posts/:id", fn(int $id) => Post::find($id), "post_show")
    ->with("id", "\d+");

$router
    ->get("/posts/{id:\d+}", fn(int $id) => Post::find($id), "post_show");

/** route with callback function */
$router->get("/posts", fn() => Post::getAll(), "post_index");

/** route invokable controller classname */
$router->get("/posts", \Namespace\MyController::class, "post_index");

/** route combining controller classname and controller action name */
$router->get("/posts", "\Namespace\MyController@index", "post_index");
//              or
$router->get("/posts", "\Namespace\MyController#index", "post_index");

/** route combining controller classname and controller action name */
$router->get("/posts", ["\Namespace\MyController", "index"], "post_index");
//              or
$router->get("/posts", ["controller" => "\Namespace\MyController", 'action' => "index"], "post_index");

$router->get("/posts", fn()=>Post::getAll(), "post_index");
$router
    ->get('posts/:id', fn(int $id)=> Post::find($id), "post-show")
    ->with("id", "\d+");
$router
    ->post('posts/:id', fn($id)=> Post::find($id)->update($_POST), "post_show")
    ->with("id", "\d+");

$request = new \GuzzleHttp\Psr7\ServerRequest("get", "/posts/1");
$route = $router->resolve($request);

// route initialization
$router
    ->post(
        "/publication/{type:[a-z]+}-{status:\d+}",
        function(ServerRequestInterface $request, string $type, int $status){
            return Post::find(["type" => $type, "status" => $status])
                ->update($request->getParsedBody())
        },
        "publication_edition"
    );

// build request instance
$request = new \ServerRequest("post", "/publication/post-1");

// process route callback. $type value will be "post" and $status value will be 1
$router->run($request);

// defining controller class
class PublicationController{

    public function __construct(private RepositoryManager $repositoryManager)
    {}

    public function index(string $type)
    {
        return $this->repositoryManager->get($type)->getAll();
    }
}

// defining repository manager class
class RepositoryManager{
    public function __construct(private \PDO $pdo)
    {}

    public function get(string $type): RepositoryInterface
    {
        // my code logic
    }
}

// container initialization
$myContainer = new \NJContainer\Container\Container(); // or nay other container
$myContainer->set(\PDO::class, $somePdoInstance); // inject pdo instance to container

$router
    ->get(
        "/publication/{type:[a-z]+}",
        "PublicationController@index", // or "PublicationController#index" or ["PublicationController", "index"]
        "publication_edition"
    )
    ->setContainer($myContainer); // Container instance will be inject during router initialization

// build request instance
$request = new \ServerRequest("get", "/publication/post");

//RepositoryManager and PublicationController instances will be automatically resolved and index method will be processed
$router->run($request);

// defining invokable middleware
class InvokableMiddleware{
    public function __invoke(ServerRequestInterface $request, $next){
        // your middleware logic code
        return $next($request);
    }
}

// defining callable middleware
class CallableMiddleware{
        public function action(ServerRequestInterface $request, $next){
        // your middleware logic code
        return $next($request);
    }
}

// defining \Psr\Http\Server\MiddlewareInterface
class PsrMiddleware implement \Psr\Http\Server\MiddlewareInterface{

        public function process(ServerRequestInterface $request, Psr\Http\Server\RequestHandlerInterface $handler){
        // your middleware logic code
        return $handler->handle($request);
    }
}

// register middlewares
$router
    ->middleware(InvokableMiddleware::class, function(RouterInterface $router){
        $router->middlewares([
            PsrMiddleware::class,
            [CallableMiddleware::class, 'action'],
            fn($request, $next) => $next($request)
        ], function($router){
            $router->post(
                "/posts/{id:\d+}",
                fn(ServerRequestInterface $request, int $id) => Post::find($id)  ->update($request->getParsedBody()),
                "post_show"
            );
        })
    })

$request = new \ServerRequest("post", "/post/1");

$router->run($request);

$router
    ->post(
        "/posts/{id:\d+}",
        fn(ServerRequestInterface $request, int $id) => Post::find($id)->update($request->getParsedBody()),
        "post_show"
    )
    ->setPolicy(fn(int $id) => $id !== 1);

$request = new \ServerRequest("post", "/post/1");

$router->run($request);