PHP code example of mezon / router

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

    

mezon / router example snippets


class MySite
{
    /**
     * Main page
     */
    public function actionIndex()
    {
        return 'This is the main page of our simple site';
    }

    /**
     * FAQ page
     */
    public function actionFaq()
    {
        return 'This is the "FAQ" page';
    }

    /**
     * Contacts page
     */
    public function actionContacts()
    {
        return 'This is the "Contacts" page';
    }

    /**
     * Some custom action handler
     */
    public function someOtherPage()
    {
        return 'Some other page of our site';
    }
    
    /**
     * Some static method
     */
    public static function someStaticMethod()
    {
        return 'Result of static method';
    }
}

$router = new \Mezon\Router\Router();
$router->fetchActions($mySite = new MySite());

$router->callRoute('/index/');

$router->fetchActions($mySite = new MySite(), [
	'Index' => 'GET',
	'Contacts' => 'POST',
	'Faq' => ['GET', 'POST'],
]);

$router->addRoute('/some-any-other-route/', [$mySite, 'someOtherPage']);

$router->addRoute('/static-route/', ['MySite', 'someStaticMethod']);
// or in this way
$router->addRoute('/static-route/', 'MySite::someStaticMethod');

function sitemap()
{
    return 'Some fake sitemap';
}

$router->addRoute('/sitemap/', 'sitemap');

$router->addRoute('/static-route/', 'MySite::someStaticMethod');
$callback = $router->getCallback('/static-route/');
var_dump($callback());

$router = new \Mezon\Router\Router();
var_dump($router->getListOfSupportedRequestMethods());

$router->addRoute('/*/', function(){});

$router->addRoute('/*/', function(){});
$router->addRoute('/index/', function(){});

$router->addRoute('/contacts/', function(){});
$router->addRoute('/*/', function(){});
$router->addRoute('/index/', function(){});

$router->addRoute('/catalogue/[i:cat_id]/', function($route, $variables){});
$router->addRoute('/catalogue/[a:cat_name]/', function($route, $variables){});

$router->addRoute('/contacts/', function(){}, 'POST'); // this handler will be called for POST requests
$router->addRoute('/contacts/', function(){}, 'GET');  // this handler will be called for GET requests
$router->addRoute('/contacts/', function(){}, 'PUT');  // this handler will be called for PUT requests
$router->addRoute('/contacts/', function(){}, 'DELETE');  // this handler will be called for DELETE requests
$router->addRoute('/contacts/', function(){}, 'OPTION');  // this handler will be called for OPTION requests
$router->addRoute('/contacts/', function(){}, 'PATCH');  // this handler will be called for PATCH requests

$router = new \Mezon\Router\Router();
$router->addRoute('/some-route/[i:id]', function(){}, 'GET', 'name of the route');
// will output /some-route/123
var_dump($router->reverse('name of the route', ['id' => 123]));

$router->dumpOnDisk('./cache/cache.php');

$router->loadFromDisk('./cache/cache.php');

$router->warmCache();

$router = new Router();
$router->addRoute('/user/[i:id]', function(string $route, array $parameters){
    $userModel = new UserModel();
    $userObject = $userModel->getUserById($parameters['id']);

    // use $userObject for any purpose you need
});

$router = new Router();

// First step. We have an API that talks JSON, convert the body
$router->registerMiddleware('*', function (string $route, array $parameters){
    $request = Request::createFromGlobals();
    
    $parameters['_request'] = $request;
    $parameters['_body'] = json_decode($request->getContent(), true);

    return $parameters;    
});

// Second step. Ensure that we are logged in when we are in the private area
$router->registerMiddleware('*', function (string $route, array $parameters){
    // Is not a private area
    if (mb_strpos($route, '/user') !== 0 || empty($parameters['user_id'])) {
        return $parameters;
    }

    $token = $parameters['_request']->headers->get('oauth_token');

    $auth = new SomeAuth();
    $auth->validateTokenOrFail(
        $token,
        $parameters['user_id']
    );

    // We don't need to return nothing
});

// Last step. Now we will modify the parameters so the handler can work with them
$router->registerMiddleware('/user/[i:user_id]', function(string $route, array $parameters){
    $userModel = new UserModel();
    
    return $userModel->getUserById(
        $parameters['user_id']
    );
});

// Final destination. We have ended the middlewares, now we can work with the processed data
$router->addRoute('/user/[i:user_id]', function (UserObject $userObject){
    // Do everything
});

$router = new Router();
$router->addRoute('/user/[i:id]', function(\Nyholm\Psr7\Request $request){
    // work here with the request in PSR-7 way

    $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();

    $responseBody = $psr17Factory->createStream('Hello world');
    $response = $psr17Factory->createResponse(200)->withBody($responseBody);
    (new \Zend\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);
});

$router->registerMiddleware('/user/[i:id]', function(string $route, array $parameters){
    $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();

    $creator = new \Nyholm\Psr7Server\ServerRequestCreator(
        $psr17Factory, // ServerRequestFactory
        $psr17Factory, // UriFactory
        $psr17Factory, // UploadedFileFactory
        $psr17Factory  // StreamFactory
    );

    return $creator->fromGlobals();
});

class DateRouterType
{

    /**
     * Method returns regexp for searching this entity in the URL
     *
     * @return string regexp for searching
     */
    public static function searchRegExp(): string
    {
        return '(\[date:'.BaseType::PARAMETER_NAME_REGEXP.'\])';
    }
}

public static function parserRegExp(): string
{
    // pretty simple regexp
    return '([0-9]{4}-[0-9]{2}-[0-9]{2})';
}

$router->addType('date', DateRouterType::class);

$router->addRoute('/posts-for-[date:posts-date]/', function(UserObject $userObject){
    // some activities here
});

$router->addRoute('/[s:some-url]/', function(UserObject $userObject){
    // some activities here
});
bash
/some-url-part/2020-02-02/ending-part/
/posts-for-2020-02-02/