Zaphpa_Router::addRoute PHP Method

addRoute() public method

Add a new route to the configured list of routes
public addRoute ( $params )
    public function addRoute($params)
    {
        if (!empty($params['path'])) {
            $template = new Zaphpa_Template($params['path']);
            if (!empty($params['handlers'])) {
                foreach ($params['handlers'] as $key => $pattern) {
                    $template->pattern($key, $pattern);
                }
            }
            $methods = array_intersect(self::$methods, array_keys($params));
            foreach ($methods as $method) {
                $this->routes[$method][$params['path']] = array('template' => $template, 'callback' => $params[$method], 'file' => !empty($params['file']) ? $params['file'] : '');
                Zaphpa_Middleware::$routes[$method][$params['path']] = $this->routes[$method][$params['path']];
            }
        }
    }

Usage Example

Beispiel #1
0
<?php

require_once __DIR__ . '/../zaphpa.lib.php';
require_once __DIR__ . '/TestController.class.php';
require_once __DIR__ . '/ZaphpaTestMiddleware.class.php';
require_once __DIR__ . '/ZaphpaTestScopedMiddleware.class.php';
$router = new Zaphpa_Router();
$router->attach('ZaphpaTestMiddleware');
$router->attach('ZaphpaAutoDocumentator', '/testapidocs');
$router->attach('ZaphpaCORS', '*')->restrict('preroute', '*', '/users');
$router->attach('ZaphpaTestScopedMiddleware')->restrict('prerender', '*', '/foo')->restrict('prerender', array('put'), '/foo/bar');
$router->addRoute(array('path' => '/users', 'get' => array('TestController', 'getTestJsonResponse')));
$router->addRoute(array('path' => '/users/{id}', 'handlers' => array('id' => Zaphpa_Constants::PATTERN_DIGIT), 'get' => array('TestController', 'getTestJsonResponse'), 'post' => array('TestController', 'getTestJsonResponse')));
$router->addRoute(array('path' => '/tags/{id}', 'handlers' => array('id' => Zaphpa_Constants::PATTERN_ALPHA), 'get' => array('TestController', 'getTestJsonResponse')));
$router->addRoute(array('path' => '/users/{user_id}/books/{book_id}', 'handlers' => array('user_id' => Zaphpa_Constants::PATTERN_NUM, 'book_id' => Zaphpa_Constants::PATTERN_ALPHA), 'get' => array('TestController', 'getTestJsonResponse')));
try {
    $router->route();
} catch (Zaphpa_InvalidPathException $ex) {
    header('Content-Type: application/json;', true, 404);
    die(json_encode(array('error' => 'not found')));
}
All Usage Examples Of Zaphpa_Router::addRoute