PHP code example of ryunosuke / microute

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

    

ryunosuke / microute example snippets


$service = new \ryunosuke\microute\Service([
    /* オプション配列 */
    'debug'              => false,
    'controllerLocation' => [
        '\\namespace\\to\\controller' => '/directory/to/controller',
    ],
    // ・・・
]);
$service->run();

    #[Redirect('/url1')] // /url1 アクセスで redirect されてこのアクションに到達します
    #[Redirect('/url2')] // /url2 アクセスで redirect されてこのアクションに到達します
    public function hogeAction() {}

#[Alias('/fuga')]
class HogeController extends \ryunosuke\microute\Web\Controller
{
    public function fooAction() {}
}

#[Scope('(?<pref_id>\d+)/')]
class HogeController extends \ryunosuke\microute\Web\Controller
{
    public function fooAction($pref_id) {}
}

    public function hogeAction($id, $seq)
    {
        // /hoge?id=foo でアクセスしても 404 になる(seq がマップできない)
    }

    public function fugaAction($id, $seq = 123)
    {
        // /fuga?id=foo でアクセスすると $id=foo, $seq=123 となる(seq はデフォルト値が使われる)
    }

    public function piyoAction(int $id, $seq = 123)
    {
        // /piyo?id=foo でアクセスすると 404 になる(foo を int 化できない)
    }

    #[Regex('/detail-(?<id>[a-z]+)/(\d+)')]
    public function testAction($id, $seq)
    {
        // /detail-foo/123 でアクセスすると $id=foo, $seq=123 となる(id は名前が一致、seq は名前がないが順番が一致)
    }

    #[Event('hoge', 10, 15)]
    public function testAction()
    {
        echo 'アクション本体';
    }
    
    public function hogeEvent($phase, $x, $y)
    {
        if ($phase === 'pre') {
            echo 'アクション前';
        }
        if ($phase === 'post') {
            echo 'アクション後';
        }
    }