Routes are a way of connecting request URLs to objects in your application. At their core routes
are a set of regular expressions that are used to match requests to destinations.
Examples:
Router::connect('/:controller/:action/*');
The first token ':controller' will be used as a controller name while the second is used as the action name.
the '/*' syntax makes this route greedy in that it will match requests like /posts/index as well as requests
like /posts/edit/1/foo/bar.
Router::connect('/home-page', array('controller' => 'pages', 'action' => 'display', 'home'));
The above shows the use of route parameter defaults, and providing routing parameters for a static route.
Router::connect(
'/:lang/:controller/:action/:id',
array(),
array('id' => '[0-9]+', 'lang' => '[a-z]{3}')
);
Shows connecting a route with custom route parameters as well as providing patterns for those parameters.
Patterns for routing parameters do not need capturing groups, as one will be added for each route params.
$defaults is merged with the results of parsing the request URL to form the final routing destination and its
parameters. This destination is expressed as an associative array by Router. See the output of {@link parse()}.
$options offers four 'special' keys. pass, named, persist and routeClass
have special meaning in the $options array.
- pass is used to define which of the routed parameters should be shifted into the pass array. Adding a
parameter to pass will remove it from the regular route array. Ex. 'pass' => array('slug')
- persist is used to define which route parameters should be automatically included when generating
new URLs. You can override persistent parameters by redefining them in a URL or remove them by
setting the parameter to false. Ex. 'persist' => array('lang')
- routeClass is used to extend and change how individual routes parse requests and handle reverse routing,
via a custom routing class. Ex. 'routeClass' => 'SlugRoute'
- named is used to configure named parameters at the route level. This key uses the same options
as Router::connectNamed()
You can also add additional conditions for matching routes to the $defaults array.
The following conditions can be used:
- [type] Only match requests for specific content types.
- [method] Only match requests with specific HTTP verbs.
- [server] Only match when $_SERVER['SERVER_NAME'] matches the given value.
Example of using the [method] condition:
Router::connect('/tasks', array('controller' => 'tasks', 'action' => 'index', '[method]' => 'GET'));
The above route will only be matched for GET requests. POST requests will fail to match this route.
public static connect ( string $route, array $defaults = [], array $options = [] ) : array | ||
$route | string | A string describing the template of the route |
$defaults | array | An array describing the default route parameters. These parameters will be used by default and can supply routing parameters that are not dynamic. See above. |
$options | array | An array matching the named elements in the route to regular expressions which that element should match. Also contains additional parameters such as which routed parameters should be shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a custom routing class. |
Résultat | array | Array of routes |
/** * Conecta una nueva ruta interpretada al enrutador * * * @param string $route * @param array $defaults * @param array $options */ function connect($route, $defaults = array(), $options = array()) { $self = I18nRouter::getInstance(); $route = $self->interpretUrl($route); //pr($route); Router::connect($route, $defaults, $options); }
public function startTest() { Configure::write('Cache.disable', false); Router::reload(); Router::connect('/:controller/:action/*', array(), array('routeClass' => 'SluggableRoute', 'models' => array('RouteTest'))); $this->RouteTest = ClassRegistry::init('RouteTest'); }
/** * Get or set version info (DB) * * @param string $extension * @param string $newVersion */ public static function version($extension = 'core', $newVersion = null) { if (SlConfigure::read('Sl.installPending')) { return SlConfigure::read('Sl.version'); } if (!SlConfigure::read('Mirror.version')) { App::import('Core', 'ConnectionManager'); $db = @ConnectionManager::getDataSource('default'); if (!$db->isConnected() || !in_array("{$db->config['prefix']}core_versions", $db->listSources())) { if (strpos(Sl::url(false), '/install') === false) { Router::connect(Sl::url(false), array('controller' => 'install')); } return; } App::import('Core', 'ClassRegistry'); ClassRegistry::init('Version')->refreshMirror(); } if ($newVersion) { $versionModel = ClassRegistry::init('Version'); $id = $versionModel->field('Version.id', array('Version.name' => $extension)); $versionModel->create(); return $versionModel->save(array('id' => $id, 'name' => $extension, 'version' => $newVersion)); } return SlConfigure::read("Mirror.version.{$extension}"); }
/** * testPasRedirect * * @return void */ public function testPasRedirect() { Router::connect('/:controller/:action/*'); $this->Controller->action = 'index'; $this->Pas->pasRedirect(array('action' => 'index')); $expected = array('action' => 'index'); $this->assertEqual($expected, $this->Controller->redirectUrl); // Test for redirect status and whether exit or not $this->Pas->pasRedirect(array('action' => 'index'), 302, false); $expected = array('action' => 'index'); $this->assertEqual($expected, $this->Controller->redirectUrl); $this->assertEqual(302, $this->Controller->redirectStatus); $this->assertEqual(false, $this->Controller->exit); $this->Controller->request->params['named'] = array('page' => 1); $this->Controller->request->query = array('foo' => 'bar'); $this->Pas->pasRedirect('/posts/index'); $expected = array('plugin' => false, 'controller' => 'posts', 'action' => 'index', 'page' => 1, '?' => array('foo' => 'bar')); $this->assertEqual($expected, $this->Controller->redirectUrl); $this->Pas->pasRedirect('/posts/index/page:2?foo=baz'); $expected = array('plugin' => false, 'controller' => 'posts', 'action' => 'index', 'page' => 2, '?' => array('foo' => 'baz')); $this->assertEqual($expected, $this->Controller->redirectUrl); // Test for named and query $this->Pas->pasRedirect(array('action' => 'index')); $expected = array('action' => 'index', 'page' => 1, '?' => array('foo' => 'bar')); $this->assertEqual($expected, $this->Controller->redirectUrl); // Test for overriding $expected = array('action' => 'index', 'page' => 2, '?' => array('foo' => 'baz')); $this->Pas->pasRedirect(array('action' => 'index', 'page' => 2, '?' => array('foo' => 'baz'))); $this->assertEqual($expected, $this->Controller->redirectUrl); }
function setUp() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller =& ClassRegistry::init('Controller'); $this->Controller->Component =& ClassRegistry::init('Component'); $this->Controller->Toolbar =& ClassRegistry::init('TestToolBarComponent', 'Component'); }
/** * set Up test case * * @return void **/ function setUp() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller =& ClassRegistry::init('Controller'); $this->View =& new DebugView($this->Controller, false); $this->_debug = Configure::read('debug'); }
function connect($route, $default = array(), $params = array()) { parent::connect($route, $default, $params); if ($route == '/') { $route = ''; } parent::connect('/:locale', $default, array_merge(array('locale' => '[a-z]{3}'), $params)); }
/** * set Up test case * * @return void **/ public function setUp() { parent::setUp(); Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller = new Controller(); $this->View = new DebugView($this->Controller, false); }
/** * This method tried to mimic the original `Router::connect` adding some * extra params and handling the insertion of necessary options to it. * * @param string $name A unique name for this route. * @param string $route A string describing the template of the route. * @param array $defaults An array describing the default route parameters. * These parameters will be used by default and can * supply routing parameters that are not dynamic. * @param array $options An array matching the named elements in the route * to regular expressions which that element should * match. Also contains additional parameters such as * which routed parameters should be shifted into the * passed arguments and supplying patterns for routing * parameters. * @return array Array of routes. */ public static function connect($name, $route, $defaults = array(), $options = array()) { $extra = array('routeClass' => 'PowerRoute'); if (!empty($name)) { $extra['routeName'] = $name; } return Router::connect($route, $defaults, array_merge($extra, $options)); }
public function registerRoutes() { $routes = new RouteCollection(); foreach ($this->routerConfiguration as $routeName => $singleRoute) { $routes->add($routeName, new Route($singleRoute['path'], $singleRoute['defaults'])); $singleRouteCakePath = preg_replace("/(\\{)(\\w+)(\\})/", ":\$2", $singleRoute['path']); Router::connect($singleRouteCakePath, $singleRoute['defaults']); } $this->routes = $routes; }
/** * Setup * * @return void */ public function setUp() { Configure::write('App.linkMap', array('blogSlug' => array('preset' => array('controller' => 'blog_posts', 'action' => 'view'), 'alias' => 'BlogPost', 'fieldMap' => array('id' => '{alias}.id', 'slug' => '{alias}.slug', 'categorySlug' => 'Category.slug'), 'titleField' => 'BlogPost.title'))); $null = null; $this->View = new View(null); $this->View->Helpers->load('Html'); $this->Link = new LinkHelper($this->View); Router::reload(); Router::connect('/article/:categorySlug/:slug-:id', array('controller' => 'blog_posts', 'action' => 'view')); }
/** * setUp * * @return void **/ function startTest() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Asset =& new AssetHelper(); $this->Asset->Html =& new HtmlHelper(); $this->Controller =& ClassRegistry::init('Controller'); if (isset($this->_debug)) { Configure::write('debug', $this->_debug); } }
/** * setUp * * @return void **/ function setUp() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Toolbar =& new ToolbarHelper(array('output' => 'DebugKit.FirePhpToolbar')); $this->Toolbar->FirePhpToolbar =& new FirePhpToolbarHelper(); $this->Controller =& ClassRegistry::init('Controller'); if (isset($this->_debug)) { Configure::write('debug', $this->_debug); } }
function startTest() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->GpsForm =& new GpsFormHelper(); $this->GpsForm->MockBackend = new MockBackendHelper(); $this->Controller =& ClassRegistry::init('Controller'); if (isset($this->_debug)) { Configure::write('debug', $this->_debug); } }
/** * setUp * * @return void **/ public function setUp() { parent::setUp(); Router::connect('/:controller/:action'); Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller = new Controller($this->getMock('CakeRequest'), new CakeResponse()); $this->View = new View($this->Controller); $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'DebugKit.FirePhpToolbar')); $this->Toolbar->FirePhpToolbar = new FirePhpToolbarHelper($this->View); $this->firecake = FireCake::getInstance(); }
/** * setUp * * @return void **/ function startTest() { Configure::write('Cache.disable', false); Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Toolbar =& new ToolbarHelper(array('output' => 'MockBackendHelper', 'cacheKey' => 'debug_kit_toolbar_test_case', 'cacheConfig' => 'default')); $this->Toolbar->MockBackend = new MockBackendHelper(); $this->Controller =& ClassRegistry::init('Controller'); if (isset($this->_debug)) { Configure::write('debug', $this->_debug); } }
function setUp() { parent::setUp(); Router::reload(); Router::connect('/projects/:project_id/timelog/:action/*', array('controller' => 'timelog'), array('project_id' => '.+')); Router::connect('/projects/:project_id/timelog/:action/:page/:sort/:direction/*', array('controller' => 'timelog'), array('project_id' => '.+')); Router::connect('timelog/:action/:id/*', array('controller' => 'timelog')); $this->Timelog = new TimelogHelper(); $this->Timelog->Html =& new HtmlHelper(); $this->Controller =& new TimelogTestController(); $this->View =& new View($this->Controller); }
public static function connect($route, $defaults = array(), $options = array()) { if (empty($options['routeClass'])) { $options['routeClass'] = 'InfinitasRoute'; } else { if ($options['routeClass'] != 'PluginShortRoute') { var_dump($options); exit; } } parent::connect($route, $defaults, $options); }
/** * set Up test case * * @return void **/ function startTest() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller =& new Controller(); $this->View =& new DebugView($this->Controller, false); $this->_debug = Configure::read('debug'); $this->_paths = array(); $this->_paths['plugins'] = App::path('plugins'); $this->_paths['views'] = App::path('views'); $this->_paths['vendors'] = App::path('vendors'); $this->_paths['controllers'] = App::path('controllers'); }
/** * setUp * * @return void **/ public function setUp() { Configure::write('Cache.disable', false); Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller = new Controller(null); $this->View = new View($this->Controller); $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'MockBackendHelper', 'cacheKey' => 'debug_kit_toolbar_test_case', 'cacheConfig' => 'default')); $this->Toolbar->MockBackend = $this->getMock('Helper', array('testMethod'), array($this->View)); if (isset($this->_debug)) { Configure::write('debug', $this->_debug); } }
/** * setUp * * @return void **/ public function setUp() { parent::setUp(); Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller = new Controller(null); $this->View = new View($this->Controller); $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'DebugKit.HtmlToolbar')); $this->Toolbar->HtmlToolbar = new HtmlToolbarHelper($this->View); $this->Toolbar->HtmlToolbar->Html = new HtmlHelper($this->View); $this->Toolbar->HtmlToolbar->Form = new FormHelper($this->View); }
/** * setUp * * @return void **/ function setUp() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Toolbar =& new ToolbarHelper(array('output' => 'DebugKit.HtmlToolbar')); $this->Toolbar->HtmlToolbar =& new HtmlToolbarHelper(); $this->Toolbar->HtmlToolbar->Html =& new HtmlHelper(); $this->Toolbar->HtmlToolbar->Form =& new FormHelper(); $this->Controller =& new Controller(); if (isset($this->_debug)) { Configure::write('debug', $this->_debug); } }
/** * Constructor for a Route. * * @param string $template Template string with parameter placeholders * @param array $defaults Array of defaults for the route. * @param array $options Array of parameters and additional options for the Route * * @return \CakeRoute */ public function __construct($template, $defaults = array(), $options = array()) { if (strpos($template, ':current_tenant') === false && empty($options['disableAutoNamedLang'])) { Router::connect($template, $defaults + array('current_tenant' => Configure::read('Config.current_tenant')), array('routeClass' => $this->name) + $options); $options += array('__promote' => true); $template = '/:current_tenant' . $template; } $options = array_merge((array) $options, array('current_tenant' => '[a-z]{1,10}')); if ($template == '/:current_tenant/') { $template = '/:current_tenant'; } parent::__construct($template, $defaults, $options); }
/** * setUp * * @return void **/ public function setUp() { parent::setUp(); Router::connect('/:controller/:action'); $request = new CakeRequest(); $request->addParams(array('controller' => 'pages', 'action' => 'display')); $this->Controller = new Controller($request, new CakeResponse()); $this->View = new View($this->Controller); $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'DebugKit.HtmlToolbar')); $this->Toolbar->HtmlToolbar = new HtmlToolbarHelper($this->View); $this->Toolbar->HtmlToolbar->Html = new HtmlHelper($this->View); $this->Toolbar->HtmlToolbar->Form = new FormHelper($this->View); }
/** * set Up test case * * @return void **/ function startTest() { Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller =& ClassRegistry::init('Controller'); $this->View =& new DebugView($this->Controller, false); $this->_debug = Configure::read('debug'); $this->_paths = array(); $this->_paths['plugin'] = Configure::read('pluginPaths'); $this->_paths['view'] = Configure::read('viewPaths'); $this->_paths['vendor'] = Configure::read('vendorPaths'); $this->_paths['controller'] = Configure::read('controllerPaths'); }
public function setUp() { $this->_initialState = array('Security' => Configure::read('Security'), 'Opauth' => Configure::read('Opauth')); Configure::write('Security.salt', 'someSalt'); Configure::write('Security.cipherSeed', 'someCipher'); Configure::write('Opauth.Strategy.Google', array('client_id' => 'googleId', 'client_secret' => 'googleSecret')); $this->Controller = $this->getMock('TestUsersController', array('redirect', 'register', 'render'), array(new CakeRequest(null, false), new CakeResponse())); $this->Controller->constructClasses(); $this->Controller->Components = $this->getMock('ComponentCollection', array('loaded')); $this->Controller->Auth = $this->getMock('AuthComponent', array('constructAuthenticate', 'login', 'user'), array($this->Controller->Components, $this->Controller->Auth->settings)); $this->Controller->Opauth = $this->getMock('OpauthComponent', array('redirectToCompleteRegistration'), array($this->Controller->Components, $this->Controller->components['Common.Opauth'])); $this->Controller->Session = $this->getMock('SessionComponent', array('setFlash', 'write'), array($this->Controller->Components)); Router::connect('/users/register', array('controller' => 'TestUsers', 'action' => 'register')); }
/** * setUp * * @return void */ public function setUp() { parent::setUp(); Configure::write('Cache.disable', false); Configure::write('debug', 2); Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); Router::parse('/'); $this->Controller = new Controller(null); $this->View = new View($this->Controller); $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'MockBackendHelper', 'cacheKey' => 'debug_kit_toolbar_test_case', 'cacheConfig' => 'default')); $this->Toolbar->MockBackend = $this->getMock('Helper', array('testMethod'), array($this->View)); $this->_viewPaths = App::path('views'); App::build(array('View' => array(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'View' . DS, APP . 'Plugin' . DS . 'DebugKit' . DS . 'View' . DS, CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'View' . DS)), true); }
/** * Constructor for a Route * Add a regex condition on the lang param to be sure it matches the available langs * * @param string $template Template string with parameter placeholders * @param array $defaults Array of defaults for the route. * @param array $options Array of parameters and additional options for the Route * @return \I18nRoute */ public function __construct($template, $defaults = array(), $options = array()) { if (strpos($template, ':lang') === false && empty($options['disableAutoNamedLang'])) { Router::connect($template, $defaults + array('lang' => DEFAULT_LANGUAGE), array('disableAutoNamedLang' => true, 'routeClass' => $this->name) + $options); $options += array('__promote' => true); $template = '/:lang' . $template; } $options = array_merge((array) $options, array('lang' => join('|', Configure::read('Config.languages')))); unset($options['disableAutoNamedLang']); if ($template == '/:lang/') { $template = '/:lang'; } parent::__construct($template, $defaults, $options); }
/** * AssetDispatcher should not 404 extensions that could be handled * by Routing. * * @return void */ public function testNoHandleRoutedExtension() { $filter = new AssetDispatcher(); $response = $this->getMock('CakeResponse', array('_sendHeader')); Configure::write('Asset.filter', array('js' => '', 'css' => '')); App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)), App::RESET); Router::parseExtensions('json'); Router::connect('/test_plugin/api/v1/:action', array('controller' => 'api')); CakePlugin::load('TestPlugin'); $request = new CakeRequest('test_plugin/api/v1/forwarding.json'); $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); $this->assertNull($filter->beforeDispatch($event)); $this->assertFalse($event->isStopped(), 'Events for routed extensions should not be stopped'); }
public function setUp() { parent::setUp(); // コンポーネントと偽のテストコントローラをセットアップする $request = new CakeRequest(); $response = $this->getMock('CakeResponse'); $this->Controller = new BcReplacePrefixTestController($request, $response); $collection = new ComponentCollection(); $collection->init($this->Controller); $this->BcReplacePrefix = new BcReplacePrefixComponent($collection); $this->BcReplacePrefix->request = $request; $this->BcReplacePrefix->response = $response; $this->Controller->Components->init($this->Controller); Router::reload(); Router::connect('/:controller/:action/*'); }