PHP code example of haikara / flat-route

1. Go to this page and download the library: Download haikara/flat-route 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/ */

    

haikara / flat-route example snippets


// ContainerInterfaceの実装を用意
$container = new Knp\Dinery\Container();

// Routerクラスをインスタンス化
$router = new Knp\FlatRoute\Router($container);

// サブディレクトリ運用の場合、ベースになるURIを設定する
$router->setBaseRoute('/knp');

$response = new Laminas\Diactoros\Response;

$router->get('/', function ($request, $args) use ($response) {
    $response->getBody()->write('<h1>トップページ</h1>');
    return $response;
}),

$router->get('/products/create', function ($request, $args) use ($response) {
    $response->getBody()->write('<h1>製品登録画面</h1>');
    return $response;
}),

$router->post('/products/store', function ($request, $args) use ($response) {
    $response->getBody()->write('<h1>製品登録処理</h1>');
    return $response;
});

// RouterにRequestを渡して実行
$request = Laminas\Diactoros\ServerRequestFactory::fromGlobals();
$response = $router->handle($request);

// Responseを出力
(new \Knp\FlatRoute\Emitter\ResponseEmitter($response))->payout();

$router->get('/', TopAction::class);

// year => 2000年以降
// month => 1月から12月
$router->get('/column/:year/:month', ColumnIndexAction::class)
    ->rule('year', Rules::integer()->min(2000))
    ->rule('month', Rules::integer()->range(1, 12));

// user_id => 英数字、10ケタ
$router->get('/profile/:user_id', UserProfileInexAction::class)
    ->rule('user_id', Rules::alnum()->length(10));

// customer_code => 数字のみ、8ケタ(0埋めありの文字列を想定)
$router->get('/customers/:customer_code/edit', CustomersEditAction::class)
    ->rule('customer_code', Rules::digit()->length(8));

// filename =>拡張子が 'jpg', 'png', 'webp'のいずれか
$router->get('/products/images/:filename', ProductsImageAction::class)
    ->rule('filename', Rules::file()->ext('jpg', 'png', 'webp'));


class Middleware1 implements MiddlewareInterface {
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        echo '1';
        $response = $handler->handle($request);
        echo '1';
        return $response;
    }
}

class Middleware2 implements MiddlewareInterface {
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        echo '2';
        $response = $handler->handle($request);
        echo '2';
        return $response;
    }
}

class Middleware3 implements MiddlewareInterface {
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        echo '3';
        $response = $handler->handle($request);
        echo '3';
        return $response;
    }
}

class Middleware4 implements MiddlewareInterface {
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        echo '4';
        $response = $handler->handle($request);
        echo '4';
        return $response;
    }
}

// ルートにMiddlewareを追加
$router->get('/main_action', function ($request, $args) use ($response) {
    echo ' Action ';
    return $response;
})
->addMiddleware(Middleware1::class)
->addMiddleware(Middleware2::class);

// ルーティング全体にMiddlewareを追加
$router->addMiddleware(Middleware3::class);
$router->addMiddleware(Middleware4::class);

// 出力される内容
// 4321 Action 1234 

// 全記事
$router->get('/column', ColumnIndexAction::class)
    ->addMiddleware(Middleware1::class);

// 特定の年の記事
$router->get('/column/:year', ColumnIndexAction::class)
    ->rule('year', Rules::integer()->min(2000))
    ->addMiddleware(Middleware1::class);

// 特定の年月の記事
$router->get('/column/:year/:month', ColumnIndexAction::class)
    ->rule('year', Rules::integer()->min(2000))
    ->rule('month', Rules::integer()->range(1, 12))
    ->addMiddleware(Middleware1::class);

// こんなのやってられない!

$router->get('/column[/:year][/:month]', ColumnIndexAction::class)
    ->rule('year', Rules::integer()->min(2000))
    ->rule('month', Rules::integer()->range(1, 12))
    ->addMiddleware(Middleware1::class);

$router->get('/column[/:year][/:month]', ColumnIndexAction::class)
    ->rule('year', Rules::integer()->min(2000))
    ->rule('month', Rules::integer()->range(1, 12))
    ->setName('ColumnIndex'); // Route::setNameでルート名を設定

// 別のルートのActionにて、ルート名を指定して NamedRoutePatterns::getRoutePathを呼ぶと、
// パラメータが割り当てられたパスの文字列を取得できる。
$router->get('/products/:product_id', function ($request, $args) use ($response) {
    $path = NamedRoutePatterns::getRoutePath(
        $request,
        'ColumnIndex',
        ['year' => 2023, 'month' => 1]
    );
     // '/column/2023/1'が得られる
     
    return $response;
});

// 通常のルーティング
$router->get('/admin/login', LoginAction::class);

// グループ化されたルーティング
$router
    ->group('/admin', function (RouteGroup $router) {
        $router->get('/products', ProductsIndexAction::class);
        $router->get('/customers', CustomersIndexAction::class);
    })
    ->addMiddleware(AuthMiddleware::class);

// ユーザー一覧画面
$router->get('/users', UsersIndexAction::class);

// ユーザー登録画面
$router->get('/users/create', UsersCreateAction::class);

// ユーザー登録処理
$router->post('/users', UsersIndexAction::class);

// ユーザー情報編集画面
$router->get('/users/:id',  UsersEditAction::class);

// ユーザー情報編集画面
$router->patch('/users/:id',  UsersUpdateAction::class);

// ユーザー削除処理
$router->delete('/users/:id',  UsersUpdateAction::class);