public function getController() { $Router = new Router(); $this->Router = $Router; $xml = new \DOMDocument(); $xml->load(__DIR__ . '/../../App/' . $this->name . '/Config/routes.xml'); $routes = $xml->getElementsByTagName('route'); // On parcourt les routes du fichier XML. foreach ($routes as $route) { $vars = []; // On regarde si des variables sont présentes dans l'URL. if ($route->hasAttribute('vars')) { $vars = explode(',', $route->getAttribute('vars')); } // On ajoute la route au routeur. $Router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars)); } try { // On récupère la route correspondante à l'URL. $matchedRoute = $Router->getRoute($this->httpRequest->requestURI()); } catch (\RuntimeException $e) { if ($e->getCode() == Router::NO_ROUTE) { // Si aucune route ne correspond, c'est que la page demandée n'existe pas. $this->httpResponse->redirect404(); } } // On ajoute les variables de l'URL au tableau $_GET. $_GET = array_merge($_GET, $matchedRoute->vars()); // On instancie le contrôleur. $controllerClass = 'App\\' . $this->name . '\\Modules\\' . $matchedRoute->module() . '\\' . $matchedRoute->module() . 'Controller'; return new $controllerClass($this, $matchedRoute->module(), $matchedRoute->action()); }
public function testUrlizeUsingAnNamedRouteThrowsIfNotApplicable() { $AuthorRoute = $this->mock('AkRoute', array('urlize' => new RouteDoesNotMatchParametersException())); $this->Router->addRoute('author', $AuthorRoute); $this->expectException('RouteDoesNotMatchParametersException'); $this->Router->author_url(array('name' => 'martin')); }
public function getController() { $router = new Router(); $xml = new \DOMDocument(); $xml->load(__DIR__ . '/../../App/' . $this->name . '/Config/route.xml'); $routes = $xml->getElementByTagName("route"); foreach ($routes as $route) { $vars = []; if ($route->hasAttribute('vars')) { $vars = explode(',', $route->getAttribute('vars')); } $router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars)); } try { $matched_route = $router->getRoute($this->httpRequest->requestURI()); } catch (\RuntimeException $exception) { if ($exception->getCode() == Router::NO_ROUTE) { $this->httpResponse->redirect404(); } } // Add variables in tab: $_GET $_GET = array_merge($_GET, $matched_route->module(), $matched_route->action()); // Instancie the controller $controller_class = 'App\\' . $this->name . '\\Modules\\' . $matched_route->module() . '\\' . $matched_route->module() . 'Controllers'; return new $controller_class($this, $matched_route->module(), $matched_route->action()); }
function testUrlizeUsingAnNamedRouteThrowsIfNotApplicable() { $AuthorRoute = $this->getMock('AkRoute', array(), array('author/:name')); $AuthorRoute->expects($this->once())->method('urlize')->with(array('name' => 'martin'))->will($this->throwException(new RouteDoesNotMatchParametersException())); $this->Router->addRoute('author', $AuthorRoute); $this->setExpectedException('RouteDoesNotMatchParametersException'); $this->Router->author_url(array('name' => 'martin')); }
public function getController() { $router = new Router(); $xml = new \DOMDocument(); $xml->load(__DIR__ . '/../../JVN/' . $this->name . '/Config/routes.xml'); $routes = $xml->getElementsByTagName('route'); foreach ($routes as $route) { $vars = []; if ($route->hasAttribute('vars')) { $vars = explode(',', $route->getAttribute('vars')); } $router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars)); } try { $matchedRoute = $router->getRoute($this->httpRequest->requestURL()); } catch (\RuntimeException $e) { if ($e->getCode() == Router::NO_ROUTE) { $this->httpResponse->redirect404(); } } $_GET = array_merge($_GET, $matchedRoute->vars()); $controllerClass = 'JVN\\' . $this->name . '\\Modules\\' . $matchedRoute->module() . '\\' . $matchedRoute->module() . 'Controller'; return new $controllerClass($this, $matchedRoute->module(), $matchedRoute->action()); }
Router::addRoute('adminNodeCreate', $aP . 'node/create', array('controller' => 'AdminNode', 'action' => 'create')); /** Blog & Comment Routes **/ Router::addRoute('adminBlogPost', $aP . 'blog', array('controller' => 'AdminBlogPost')); Router::addRoute('adminBlogPostPaged', $aP . 'blog/page-:page', array('controller' => 'AdminBlogPost')); Router::addRoute('adminBlogPostId', $aP . 'blog/:id/:action', array('controller' => 'AdminBlogPost')); Router::addRoute('adminBlogPostCreate', $aP . 'blog/:action', array('controller' => 'AdminBlogPost')); Router::addRoute('adminBlogPostSearch', $aP . 'blog/search/:q', array('controller' => 'AdminBlogPost', 'action' => 'search', 'q' => false, 'fields' => array('headline', 'BlogPost.id', 'tags'))); /** Comment Routes **/ Router::addRoute('adminComment', $aP . 'comment', array('controller' => 'AdminComment')); Router::addRoute('adminCommentBlogPost', $aP . 'comment/blogPost/:blogPostId', array('controller' => 'AdminComment')); Router::addRoute('adminCommentPaged', $aP . 'comment/page-:page', array('controller' => 'AdminComment')); Router::addRoute('adminCommentId', $aP . 'comment/:id/:action', array('controller' => 'AdminComment', 'action' => 'edit')); /** Media Files **/ Router::addRoute('adminMediaFiles', $aP . 'files/', array('controller' => 'AdminFolder', 'action' => 'view')); Router::addRoute('adminMediaFilesPaged', $aP . 'files/page-:page', array('controller' => 'AdminFolder', 'action' => 'view')); Router::addRoute('adminMediaFileSearch', $aP . 'files/search/:q', array('controller' => 'AdminMediaFile', 'action' => 'search', 'q' => false, 'fields' => 'filename')); Router::addRoute('adminMediaFileId', $aP . 'files/:id/:action', array('controller' => 'AdminMediaFile', 'action' => 'edit')); Router::addRoute('adminMediaUpload', $aP . 'files/upload/', array('controller' => 'AdminMediaFile', 'action' => 'upload')); Router::addRoute('adminMediaFileMove', $aP . 'files/:id/:action/(?P<direction>up|down|top|bottom)', array('controller' => 'AdminMediaFile')); /** Folder Routes **/ Router::addRoute('adminFolderCreate', $aP . 'folder/create/', array('controller' => 'AdminFolder', 'action' => 'create')); Router::addRoute('adminFolderView', $aP . 'folder/:id/', array('controller' => 'AdminFolder', 'action' => 'view')); Router::addRoute('adminFolderViewPaged', $aP . 'folder/:id/page-:page', array('controller' => 'AdminFolder', 'action' => 'view')); Router::addRoute('adminFolderUpload', $aP . 'folder/:folder_id/upload', array('controller' => 'AdminMediaFile', 'action' => 'upload')); Router::addRoute('adminFolderId', $aP . 'folder/:id/:action', array('controller' => 'AdminFolder')); /** scaffold **/ Router::addRoute('adminScaffold', $aP . ':controller/:action', array('action' => 'index', 'controllerPrefix' => 'Admin')); Router::addRoute('adminScaffoldId', $aP . ':controller/:id/:action', array('action' => 'index', 'controllerPrefix' => 'Admin')); /** 404 Route for admin pages too **/ Router::addRoute('admin404', $aP . '*', array('controller' => 'Error', 'action' => '404'));
// require the libraries which we will be using require_once INCLUDE_DIR . '/PageError/PageError.php'; require_once INCLUDE_DIR . '/php-router/php-router.php'; require_once INCLUDE_DIR . '/Twig/lib/Twig/Autoloader.php'; // register the Twig Autoloader Twig_Autoloader::register(); // Create a new instance of Router $router = new Router(); // Get an instance of Dispatcher $dispatcher = new Dispatcher(); $dispatcher->setSuffix('Controller'); $dispatcher->setClassPath(CONTROLLER_DIR); // Set up your default route: $default_route = new Route('/'); $default_route->setMapClass('default')->setMapMethod('index'); $router->addRoute('default', $default_route); $url = urldecode($_SERVER['REQUEST_URI']); try { $found_route = $router->findRoute($url); $dispatcher->dispatch($found_route); } catch (RouteNotFoundException $e) { PageError::show('404', $url); } catch (badClassNameException $e) { PageError::show('400', $url); } catch (classFileNotFoundException $e) { PageError::show('500', $url); } catch (classNameNotFoundException $e) { PageError::show('500', $url); } catch (classMethodNotFoundException $e) { PageError::show('500', $url); } catch (classNotSpecifiedException $e) {
Router::addRoute('^(?P<route>.*)$', array('PermalinkController', 'handle')); /** * Specific routes next */ // Main Index Router::addRoute('^/$', 'home.php'); // About page Router::addRoute('^/about/?(.*)', 'about.php'); // Admin section Router::addRoute('^/admin/?(.*)', 'admin/index.php'); // Downloads and API Router::addRoute('^/downloads/?(.*)', 'downloads/index.php'); // Search Router::addRoute('^/search/?(.*)', 'search.php'); // Browse Router::addRoute('^/browse/?(.*)', array('StructureController', 'handle')); // New activation Router::addRoute('^/api-key/activate/(?P<secret>.*)', array('ApiKeyController', 'activateKey')); // Old activation Router::addRoute('^/api-key/\\?secret=(?P<secret>.*)', array('ApiKeyController', 'activateKey')); // Create an API Key Router::addRoute('^/api-key/$', array('ApiKeyController', 'requestKey')); /** * Dynamic routes last, most specific to least specific */ // API Router::addRoute('^/api/((?P<api_version>([0-9]+)\\.([0-9]+))/)?(?P<operation>structure|law|)(?P<route>/.*)', array('APIPermalinkController', 'handle')); Router::addRoute('^/api/((?P<api_version>([0-9]+)\\.([0-9]+))/)?dictionary/((?P<term>.*)/)?', array('APIDictionaryController', 'handle')); Router::addRoute('^/api/((?P<api_version>([0-9]+)\\.([0-9]+))/)?search/(?P<term>.*)/', array('APISearchController', 'handle')); Router::addRoute('^/api/((?P<api_version>([0-9]+)\\.([0-9]+))/)?suggest/(?P<term>.*)/', array('APISuggestController', 'handle'));
} require "config.php"; foreach (glob("models/*.php") as $file) { require_once $file; } require_once 'PublicDesign.php'; require_once 'PublicSection.php'; $router = new Router(); $rId = '([^/|\\-]+)'; $rDir = '([^/]+)'; $rNum = '([0-9]+)'; $rExtra = '(?:-[^/]*)?'; $rIdExtra = "{$rId}{$rExtra}"; $rNumExtra = "{$rNum}{$rExtra}"; if (Team::isAdmin()) { $router->addRoute("/unete/", array('JoinUs')); } $router->addRoute("/normas/", array('Rules')); $router->addRoute("/votaciones/", array('Polls')); $router->addRoute("/votaciones/crear/", array('AddPoll')); $router->addRoute("/votaciones/{$rNum}/", array('ViewPoll')); $router->addRoute("/admin/", array('Admin_Index')); $router->addRoute("/admin/comunicados/", array('Admin_Notices')); $router->addRoute("/admin/equipos/", array('Admin_Teams')); $router->addRoute("/admin/equipos/{$rNum}/", array('Admin_Team')); $router->addRoute("/admin/temporadas/", array('Admin_Seasons')); $router->addRoute("/admin/temporadas/{$rNum}/", array('Admin_Season')); $router->addRoute("/admin/temporadas/{$rNum}/jornadas/", array('Admin_Season_Weeks')); $router->addRoute("/admin/temporadas/{$rNum}/eventos/", array('Admin_Season_Events')); $router->addRoute("/", array('Index')); $router->addRoute("/batch/", array('Batch'));
public function testQueryParameters() { $router = new Router(); $route = new Route("/2008-08-01/Accounts/:id/IncomingPhoneNumbers"); $route->setMapClass('IncomingPhoneNumbers')->setMapMethod('list'); $route->addDynamicElement(':id', ':id'); $router->addRoute('test', $route); $found = $router->findRoute('/2008-08-01/Accounts/1/IncomingPhoneNumbers?a=1&b=2'); $this->assertSame($found, $route); }
/* Only load the class if the name contains accepted characters */ if (preg_match('/[a-z]/i', $class)) { require_once __DIR__ . '/app/' . $class . '.php'; } } /* GET /user/13214/edit/ */ Router::addRoute('GET', '/events/(?<event_id>[0-9]+)/?', function ($args) { $event_id = $args['event_id']; $feedContents = file_get_contents('http://www.skiddle.com/api/v1/events/' . $event_id . '/?api_key=838cec44cf59198b22731f4be213988a'); $feedArray = json_decode($feedContents, true); echo json_encode($feedArray['results']); }); Router::addRoute('GET', '/images/\\?search=(?<search>[A-Za-z0-9\\% ]+)&count=(?<count>[0-9]+)', function ($args) { $search = $_GET['search']; $count = $_GET['count']; echo json_encode(searchImages($search, $count)); }); //List all the events Router::addRoute('GET', '/events/?', function () { $feedContents = file_get_contents('http://www.skiddle.com/api/v1/events/?api_key=838cec44cf59198b22731f4be213988a&eventcode=FEST&offset=0'); $feedArray = json_decode($feedContents, true); echo json_encode($feedArray['results']); }); /* GET /user/ */ Router::addRoute('GET', '/user/?', function () { echo 'List all users'; }); /* GET / */ Router::addRoute('GET', '/?', function () { echo 'Home'; });
<?php require 'config/configs.php'; require 'core/autoloader.php'; //create new router $router = new Router(); //add new custom routes url-controller-method-type $router->addRoute("yes/go", "help", "func2", "put,post"); //custom route with parameters $router->addRoute("show/result/{param}/{param}", "help", "myfunc", "get"); $router->addRoute("Result/Page/{param}", "dbController", "dbTest", "get"); //simple routing $router->addRoute("ok/good", "test", "f2", "post"); $router->addRoute("billu/barber", "help", "func2", "get"); //RESTful Routing $router->addRoute("restful/put", "test", "rest", "put"); $router->addRoute("blog/page/{param}/{param}/sort/{param}/year/{param}", "test", "fourargs", "any"); $router->addRoute("work", "test", "f2", "get"); $router->addRoute("category/{param}/year/{param}/month/{param}", "test", "threeargs", "get"); // changed order from 2 to 1 //initialize the router $router->initialize();
<?php // Set up redirects Router::addRoute('', 'hello/world'); Router::addRoute('docs', 'docs/overview');
public static function post($mask, $callback) { $route = new static('post', $mask, $callback); return Router::addRoute($route); }
/** * Get the router. * @return Router The router. */ public function router() { if (empty($this->router)) { $router = new Router(); $configPath = __DIR__ . '/../etc/app/' . $this->name; $dir = opendir($configPath); if ($dir === false) { throw new \RuntimeException('Failed to open config directory "' . $configPath . '"'); } $modules = array(); while (false !== ($module = readdir($dir))) { // Notice that "." is a valid module name // In fact, you can create a routes file like this : $configPath.'/routes.json' if ($module == '..') { continue; } if (!is_dir($configPath . '/' . $module)) { continue; } $modules[] = $module; } closedir($dir); //Sorting modules is important : //"." must be at the begining, because it has the greatest priority sort($modules); foreach ($modules as $module) { $routesPath = $configPath . '/' . $module . '/routes.json'; if (file_exists($routesPath)) { $json = file_get_contents($routesPath); if ($json === false) { continue; } $routes = json_decode($json, true); if ($routes === null) { continue; } foreach ($routes as $route) { $varsNames = isset($route['vars']) && is_array($route['vars']) ? $route['vars'] : array(); if ($module == '.') { //Global route $routeModule = $route['module']; } else { $routeModule = $module; } $router->addRoute(new Route($route['url'], $routeModule, $route['action'], $varsNames)); } } } $this->router = $router; } return $this->router; }
<?php namespace Acme\Rest; require __DIR__ . '/../src/autoload.php'; $router = new Router(); $application = new Application($router); $router->addRoute(new Route('get', '/', new IndexRequestHandler())); $response = $application->run(new HttpRequest($_SERVER)); $response->flush();
require_once KERNEL_DIR . '/Router.php'; require_once KERNEL_DIR . '/Container.php'; require_once CONTROLLER_DIR . '/LoginController.php'; require_once CONTROLLER_DIR . '/RoutingController.php'; require_once CONTROLLER_DIR . '/DatabaseController.php'; require_once MODEL_DIR . '/ImageModel.php'; require_once MODEL_DIR . '/UserModel.php'; session_start(); $connection = new PDO('mysql:host=127.0.0.1;dbname=imagegallery;charset=utf8mb4', 'root', 'emil0609'); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $container = new Container(); $container->bindArguments('RoutingController', ['connection' => $connection, 'container' => $container]); $container->bindArguments('ImageModel', ['connection' => $connection]); $container->bindArguments('UserModel', ['connection' => $connection]); $router = new Router(); $router->addRoute('GET', '/', ['RoutingController', 'renderLoginView']); $router->addRoute('POST', '/login', ['LoginController', 'login']); $router->addRoute('GET', '/gallery', ['RoutingController', 'renderGalleryView']); $router->addRoute('GET', '/logout', ['LoginController', 'logout']); $router->addRoute('GET', '/upload', ['RoutingController', 'renderUploadView']); $router->addRoute('GET', '/users', ['RoutingController', 'renderUsersView']); $router->addRoute('GET', '/create', ['RoutingController', 'test']); $router->addRoute('GET', '/delete', ['UserModel', 'deleteUser']); $router->addRoute('GET', '/getusers', ['UserModel', 'getUsers']); $router->addRoute('POST', '/createimage', ['ImageModel', 'createImage']); $router->addRoute('GET', '/getimages', ['ImageModel', 'getImages']); $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $route = $router->match($_SERVER['REQUEST_METHOD'], $uri); if ($route == null) { $route = ['handle' => ['ErrorController', 'error404'], 'arguments' => []]; }
* actions including possible parameters. * * @package app * @subpackage app.config */ /** Admin Routes **/ require dirname(__FILE__) . '/adminRoutes.php'; // general error route Router::addRoute('error', 'error/:action', array('controller' => 'Error')); /** Website Routes **/ /** Image Thumbnails **/ Router::addRoute('imageSrc', 'static/img/public/:unique_id/(?P<width>\\d+|auto)x(?P<height>\\d+|auto)/(?P<method>(resize|resizeCrop|auto))/:filename', array('controller' => 'MediaFile', 'action' => 'thumb')); /** Node Routes **/ Router::addRoute('root', '/', array('controller' => 'Node')); Router::addRoute('nodeView', 'page/:uri', array('controller' => 'Node', 'action' => 'view')); /** Blog Routes **/ Router::addRoute('root', '/', array('controller' => 'BlogPost')); Router::addRoute('blog', 'blog', array('controller' => 'BlogPost')); Router::addRoute('blogRSS', 'blog/rss', array('controller' => 'BlogPost', 'layout' => 'rss')); Router::addRoute('blogICal', 'blog/ical', array('controller' => 'BlogPost', 'layout' => 'vcal')); Router::addRoute('blogTxt', 'blog/txt', array('controller' => 'BlogPost', 'layout' => 'txt')); Router::addRoute('blogCommentsRSS', 'blog/comment/rss', array('controller' => 'Comment', 'action' => 'rss')); Router::addRoute('blogSearch', 'blog/search/:q', array('controller' => 'BlogPost', 'action' => 'search')); Router::addRoute('blogPostSearchPaged', 'blog/search/:q/page-:page', array('controller' => 'BlogPost', 'action' => 'search')); Router::addRoute('blogSearch2', 'blog/search', array('controller' => 'BlogPost', 'action' => 'search')); Router::addRoute('BlogPostPaged', 'blog/page-:page', array('controller' => 'BlogPost')); Router::addRoute('blogEntryId', 'blog/:id/', array('controller' => 'BlogPost', 'action' => 'view')); Router::addRoute('blogEntryUri', 'blog/:uri/', array('controller' => 'BlogPost', 'action' => 'view')); /** Language Change **/ Router::addRoute('rootLanguage', '/:language_id/', array('controller' => 'Node'));