# 路由(Routing)
# 路由(Routing)
The router component allows defining routes that are mapped to controllers or handlers that should receivethe request. A router simply parses a URI to determine this information. The router has two modes: MVCmode and match-only mode. The first mode is ideal for working with MVC applications.
路由器组件用来定义处理接收到的请求的路由,指向相应的控制器或者处理程序。路由器只是简单解析一个URI获取这些信息。路由器有两种模式:MVC模式以及匹配模式。第一种模式主要适合MVC应用。
### 定义路由(Defining Routes)
[*Phalcon\\Mvc\\Router*](#) provides advanced routing capabilities. In MVC mode,you can define routes and map them to controllers/actions that you require. A route is defined as follows:
[*Phalcon\\Mvc\\Router*](#) 提供高级路由支持。在MVC模式下,你可以定义路由并映射向需要的控制器/动作。一个路由定义方法如下所示:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
// Create the router
$router = new Router();
// Define a route
$router->add(
"/admin/users/my-profile",
array(
"controller" => "users",
"action" => "profile"
)
);
// Another route
$router->add(
"/admin/users/change-password",
array(
"controller" => "users",
"action" => "changePassword"
)
);
$router->handle();
```
```
add() 方法接受一个匹配模式作为第一个参数,一组可选的路径作为第二个参数。如上,如果URI就是/admin/users/my-profile的话,那么 “users” 控制的 “profile” 方法将被调用。当然路由器并不马上就调用这个方法,它只是收集这些信息并且通知相应的组件(比如 [*Phalcon\\Mvc\\Dispatcher*](#) )应该调用这个控制器的这个动作。
一个应用程序可以由很多路径,一个一个定义是一个非常笨重的工作。这种情况下我们可以创建一个更加灵活的路由:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
// Create the router
$router = new Router();
// Define a route
$router->add(
"/admin/:controller/a/:action/:params",
array(
"controller" => 1,
"action" => 2,
"params" => 3
)
);
```
```
在上面的例子中我们通过使用通配符定义了一个可以匹配多个URI的路由,比如,访问这个URL(/admin/users/a/delete/dave/301),那么:
ControllerusersActiondeleteParameterdaveParameter301The method add() receives a pattern that optionally could have predefined placeholders and regular expressionmodifiers. All the routing patterns must start with a slash character (/). The regular expression syntax usedis the same as the [PCRE regular expressions](http://www.php.net/manual/en/book.pcre.php). Note that, it is not necessary to add regular expressiondelimiters. All routes patterns are case-insensitive.
The second parameter defines how the matched parts should bind to the controller/action/parameters. Matchingparts are placeholders or subpatterns delimited by parentheses (round brackets). In the example given above, thefirst subpattern matched (:controller) is the controller part of the route, the second the action and so on.
These placeholders help writing regular expressions that are more readable for developers and easierto understand. The following placeholders are supported:
PlaceholderRegular ExpressionUsage/:module/(\[a-zA-Z0-9\_-\]+)Matches a valid module name with alpha-numeric characters only/:controller/(\[a-zA-Z0-9\_-\]+)Matches a valid controller name with alpha-numeric characters only/:action/(\[a-zA-Z0-9\_\]+)Matches a valid action name with alpha-numeric characters only/:params(/.*)*Matches a list of optional words separated by slashes. Use only this placeholder at the end of a route/:namespace/(\[a-zA-Z0-9\_-\]+)Matches a single level namespace name/:int/(\[0-9\]+)Matches an integer parameterController names are camelized, this means that characters (-) and (\_) are removed and the next characteris uppercased. For instance, some\_controller is converted to SomeController.
Since you can add many routes as you need using add(), the order in which routes are added indicatetheir relevance, latest routes added have more relevance than first added. Internally, all defined routesare traversed in reverse order until [*Phalcon\\Mvc\\Router*](#) finds theone that matches the given URI and processes it, while ignoring the rest.
### 参数名称(Parameters with Names)
The example below demonstrates how to define names to route parameters:
```
<pre class="calibre14">```
<?php
$router->add(
"/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params",
array(
"controller" => "posts",
"action" => "show",
"year" => 1, // ([0-9]{4})
"month" => 2, // ([0-9]{2})
"day" => 3, // ([0-9]{2})
"params" => 4 // :params
)
);
```
```
In the above example, the route doesn't define a “controller” or “action” part. These parts are replacedwith fixed values (“posts” and “show”). The user will not know the controller that is really dispatchedby the request. Inside the controller, those named parameters can be accessed as follows:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function showAction()
{
// Return "year" parameter
$year = $this->dispatcher->getParam("year");
// Return "month" parameter
$month = $this->dispatcher->getParam("month");
// Return "day" parameter
$day = $this->dispatcher->getParam("day");
}
}
```
```
Note that the values of the parameters are obtained from the dispatcher. This happens because it is thecomponent that finally interacts with the drivers of your application. Moreover, there is also anotherway to create named parameters as part of the pattern:
```
<pre class="calibre14">```
<?php
$router->add(
"/documentation/{chapter}/{name}.{type:[a-z]+}",
array(
"controller" => "documentation",
"action" => "show"
)
);
```
```
You can access their values in the same way as before:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class DocumentationController extends Controller
{
public function showAction()
{
// Returns "name" parameter
$name = $this->dispatcher->getParam("name");
// Returns "type" parameter
$type = $this->dispatcher->getParam("type");
}
}
```
```
### 短语法(Short Syntax)
If you don't like using an array to define the route paths, an alternative syntax is also available.The following examples produce the same result:
```
<pre class="calibre14">```
<?php
// Short form
$router->add("/posts/{year:[0-9]+}/{title:[a-z\-]+}", "Posts::show");
// Array form
$router->add(
"/posts/([0-9]+)/([a-z\-]+)",
array(
"controller" => "posts",
"action" => "show",
"year" => 1,
"title" => 2
)
);
```
```
### 混合使用数组和短语法(Mixing Array and Short Syntax)
Array and short syntax can be mixed to define a route, in this case note that named parameters automaticallyare added to the route paths according to the position on which they were defined:
```
<pre class="calibre14">```
<?php
// First position must be skipped because it is used for
// the named parameter 'country'
$router->add('/news/{country:[a-z]{2}}/([a-z+])/([a-z\-+])',
array(
'section' => 2, // Positions start with 2
'article' => 3
)
);
```
```
### 路由到模块(Routing to Modules)
You can define routes whose paths include modules. This is specially suitable to multi-module [applications.It](http://applications.It)'s possible define a default route that includes a module wildcard:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
$router = new Router(false);
$router->add('/:module/:controller/:action/:params', array(
'module' => 1,
'controller' => 2,
'action' => 3,
'params' => 4
));
```
```
In this case, the route always must have the module name as part of the URL. For example, the followingURL: /admin/users/edit/sonny, will be processed as:
ModuleadminControllerusersActioneditParametersonnyOr you can bind specific routes to specific modules:
```
<pre class="calibre14">```
<?php
$router->add(
"/login",
array(
'module' => 'backend',
'controller' => 'login',
'action' => 'index'
)
);
$router->add(
"/products/:action",
array(
'module' => 'frontend',
'controller' => 'products',
'action' => 1
)
);
```
```
Or bind them to specific namespaces:
```
<pre class="calibre14">```
<?php
$router->add(
"/:namespace/login",
array(
'namespace' => 1,
'controller' => 'login',
'action' => 'index'
)
);
```
```
Namespaces/class names must be passed separated:
```
<pre class="calibre14">```
<?php
$router->add(
"/login",
array(
'namespace' => 'Backend\Controllers',
'controller' => 'login',
'action' => 'index'
)
);
```
```
### 限制 HTTP 请求传入方式(HTTP Method Restrictions)
When you add a route using simply add(), the route will be enabled for any HTTP method. Sometimes we can restrict a route to a specific method,this is especially useful when creating RESTful applications:
```
<pre class="calibre14">```
<?php
// This route only will be matched if the HTTP method is GET
$router->addGet("/products/edit/{id}", "Products::edit");
// This route only will be matched if the HTTP method is POST
$router->addPost("/products/save", "Products::save");
// This route will be matched if the HTTP method is POST or PUT
$router->add("/products/update", "Products::update")->via(array("POST", "PUT"));
```
```
### 使用转换(Using convertions)
Convertions allow to freely transform the route's parameters before passing them to the dispatcher, the following examples show how to use them:
```
<pre class="calibre14">```
<?php
// The action name allows dashes, an action can be: /products/new-ipod-nano-4-generation
$router
->add('/products/{slug:[a-z\-]+}', array(
'controller' => 'products',
'action' => 'show'
))
->convert('slug', function ($slug) {
// Transform the slug removing the dashes
return str_replace('-', '', $slug);
});
```
```
### 路由分组(Groups of Routes)
If a set of routes have common paths they can be grouped to easily maintain them:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;
$router = new Router();
// Create a group with a common module and controller
$blog = new RouterGroup(
array(
'module' => 'blog',
'controller' => 'index'
)
);
// All the routes start with /blog
$blog->setPrefix('/blog');
// Add a route to the group
$blog->add('/save', array(
'action' => 'save'
));
// Add another route to the group
$blog->add('/edit/{id}', array(
'action' => 'edit'
));
// This route maps to a controller different than the default
$blog->add('/blog', array(
'controller' => 'blog',
'action' => 'index'
));
// Add the group to the router
$router->mount($blog);
```
```
You can move groups of routes to separate files in order to improve the organization and code reusing in the application:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router\Group as RouterGroup;
class BlogRoutes extends RouterGroup
{
public function initialize()
{
// Default paths
$this->setPaths(
array(
'module' => 'blog',
'namespace' => 'Blog\Controllers'
)
);
// All the routes start with /blog
$this->setPrefix('/blog');
// Add a route to the group
$this->add(
'/save',
array(
'action' => 'save'
)
);
// Add another route to the group
$this->add(
'/edit/{id}',
array(
'action' => 'edit'
)
);
// This route maps to a controller different than the default
$this->add(
'/blog',
array(
'controller' => 'blog',
'action' => 'index'
)
);
}
}
```
```
Then mount the group in the router:
```
<pre class="calibre14">```
<?php
// Add the group to the router
$router->mount(new BlogRoutes());
```
```
### 匹配路由(Matching Routes)
A valid URI must be passed to Router in order to let it checks the route that matches that given [URI.By](http://URI.By) default, the routing URI is taken from the $\_GET\[‘\_url'\] variable that is created by the rewrite enginemodule. A couple of rewrite rules that work very well with Phalcon are:
```
<pre class="calibre14">```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
```
```
The following example shows how to use this component in stand-alone mode:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
// Creating a router
$router = new Router();
// Define routes here if any
// ...
// Taking URI from $_GET["_url"]
$router->handle();
// Or Setting the URI value directly
$router->handle("/employees/edit/17");
// Getting the processed controller
echo $router->getControllerName();
// Getting the processed action
echo $router->getActionName();
// Get the matched route
$route = $router->getMatchedRoute();
```
```
### 路由命名(Naming Routes)
Each route that is added to the router is stored internally as an object [*Phalcon\\Mvc\\Router\\Route*](#).That class encapsulates all the details of each route. For instance, we can give a name to a path to identify it uniquely in our application.This is especially useful if you want to create URLs from it.
```
<pre class="calibre14">```
<?php
$route = $router->add("/posts/{year}/{title}", "Posts::show");
$route->setName("show-posts");
// Or just
$router->add("/posts/{year}/{title}", "Posts::show")->setName("show-posts");
```
```
Then, using for example the component [*Phalcon\\Mvc\\Url*](#) we can build routes from its name:
```
<pre class="calibre14">```
<?php
// Returns /posts/2012/phalcon-1-0-released
echo $url->get(
array(
"for" => "show-posts",
"year" => "2012",
"title" => "phalcon-1-0-released"
)
);
```
```
### 范例(Usage Examples)
The following are examples of custom routes:
```
<pre class="calibre14">```
<?php
// Matches "/system/admin/a/edit/7001"
$router->add(
"/system/:controller/a/:action/:params",
array(
"controller" => 1,
"action" => 2,
"params" => 3
)
);
// Matches "/es/news"
$router->add(
"/([a-z]{2})/:controller",
array(
"controller" => 2,
"action" => "index",
"language" => 1
)
);
// Matches "/es/news"
$router->add(
"/{language:[a-z]{2}}/:controller",
array(
"controller" => 2,
"action" => "index"
)
);
// Matches "/admin/posts/edit/100"
$router->add(
"/admin/:controller/:action/:int",
array(
"controller" => 1,
"action" => 2,
"id" => 3
)
);
// Matches "/posts/2015/02/some-cool-content"
$router->add(
"/posts/([0-9]{4})/([0-9]{2})/([a-z\-]+)",
array(
"controller" => "posts",
"action" => "show",
"year" => 1,
"month" => 2,
"title" => 4
)
);
// Matches "/manual/en/translate.adapter.html"
$router->add(
"/manual/([a-z]{2})/([a-z\.]+)\.html",
array(
"controller" => "manual",
"action" => "show",
"language" => 1,
"file" => 2
)
);
// Matches /feed/fr/le-robots-hot-news.atom
$router->add(
"/feed/{lang:[a-z]+}/{blog:[a-z\-]+}\.{type:[a-z\-]+}",
"Feed::get"
);
// Matches /api/v1/users/peter.json
$router->add(
'/api/(v1|v2)/{method:[a-z]+}/{param:[a-z]+}\.(json|xml)',
array(
'controller' => 'api',
'version' => 1,
'format' => 4
)
);
```
```
> Beware of characters allowed in regular expression for controllers and namespaces. As thesebecome class names and in turn they're passed through the file system could be used by attackers toread unauthorized files. A safe regular expression is: /(\[a-zA-Z0-9\_-\]+)
### 默认行为(Default Behavior)
[*Phalcon\\Mvc\\Router*](#) has a default behavior providing a very simple routing thatalways expects a URI that matches the following pattern: /:controller/:action/:params
For example, for a URL like this *<http://phalconphp.com/documentation/show/about.html>*, this router will translate it as follows:
ControllerdocumentationActionshowParameterabout.htmlIf you don't want use this routes as default in your application, you must create the router passing false as parameter:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
// Create the router without default routes
$router = new Router(false);
```
```
### 设置默认路由(Setting the default route)
When your application is accessed without any route, the ‘/' route is used to determine what paths must be used to show the initial pagein your website/application:
```
<pre class="calibre14">```
<?php
$router->add(
"/",
array(
'controller' => 'index',
'action' => 'index'
)
);
```
```
### 没有找到路径(Not Found Paths)
If none of the routes specified in the router are matched, you can define a group of paths to be used in this scenario:
```
<pre class="calibre14">```
<?php
// Set 404 paths
$router->notFound(
array(
"controller" => "index",
"action" => "route404"
)
);
```
```
### 设置默认路径(Setting default paths)
It's possible to define default values for common paths like module, controller or action. When a route is missing any ofthose paths they can be automatically filled by the router:
可以为通用路径中的 module, controller, action 定义默认值。当一个路由缺少其中任何一项时,路由器可以自动用默认值填充:
```
<pre class="calibre14">```
<?php
// Setting a specific default
$router->setDefaultModule('backend');
$router->setDefaultNamespace('Backend\Controllers');
$router->setDefaultController('index');
$router->setDefaultAction('index');
// Using an array
$router->setDefaults(
array(
'controller' => 'index',
'action' => 'index'
)
);
```
```
### 处理结尾额外的斜杆(Dealing with extra/trailing slashes)
Sometimes a route could be accessed with extra/trailing slashes and the end of the route, those extra slashes would lead to producea not-found status in the dispatcher. You can set up the router to automatically remove the slashes from the end of handled route:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
$router = new Router();
// Remove trailing slashes automatically
$router->removeExtraSlashes(true);
```
```
Or, you can modify specific routes to optionally accept trailing slashes:
```
<pre class="calibre14">```
<?php
$router->add(
'/{language:[a-z]{2}}/:controller[/]{0,1}',
array(
'controller' => 2,
'action' => 'index'
)
);
```
```
### 匹配回调函数(Match Callbacks)
Sometimes, routes must be matched if they meet specific conditions, you can add arbitrary conditions to routes using the‘beforeMatch' callback, if this function return false, the route will be treaded as non-matched:
```
<pre class="calibre14">```
<?php
$router->add('/login', array(
'module' => 'admin',
'controller' => 'session'
))->beforeMatch(function ($uri, $route) {
// Check if the request was made with Ajax
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') {
return false;
}
return true;
});
```
```
You can re-use these extra conditions in classes:
```
<pre class="calibre14">```
<?php
class AjaxFilter
{
public function check()
{
return $_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest';
}
}
```
```
And use this class instead of the anonymous function:
```
<pre class="calibre14">```
<?php
$router->add('/get/info/{id}', array(
'controller' => 'products',
'action' => 'info'
))->beforeMatch(array(new AjaxFilter(), 'check'));
```
```
### 限制主机名(Hostname Constraints)
The router allow to set hostname constraints, this means that specific routes or a group of routes can be restrictedto only match if the route also meets the hostname constraint:
```
<pre class="calibre14">```
<?php
$router->add('/login', array(
'module' => 'admin',
'controller' => 'session',
'action' => 'login'
))->setHostName('admin.company.com');
```
```
Hostname can also be regular expressions:
```
<pre class="calibre14">```
<?php
$router->add('/login', array(
'module' => 'admin',
'controller' => 'session',
'action' => 'login'
))->setHostName('([a-z+]).company.com');
```
```
In groups of routes you can set up a hostname constraint that apply for every route in the group:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router\Group as RouterGroup;
// Create a group with a common module and controller
$blog = new RouterGroup(
array(
'module' => 'blog',
'controller' => 'posts'
)
);
// Hostname restriction
$blog->setHostName('blog.mycompany.com');
// All the routes start with /blog
$blog->setPrefix('/blog');
// Default route
$blog->add('/', array(
'action' => 'index'
));
// Add a route to the group
$blog->add('/save', array(
'action' => 'save'
));
// Add another route to the group
$blog->add('/edit/{id}', array(
'action' => 'edit'
));
// Add the group to the router
$router->mount($blog);
```
```
### URI 来源(URI Sources)
By default the URI information is obtained from the $\_GET\[‘\_url'\] variable, this is passed by the Rewrite-Engine toPhalcon, you can also use $\_SERVER\[‘REQUEST\_URI'\] if required:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
// ...
$router->setUriSource(Router::URI_SOURCE_GET_URL); // Use $_GET['_url'] (default)
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); // Use $_SERVER['REQUEST_URI'] (default)
```
```
Or you can manually pass a URI to the ‘handle' method:
```
<pre class="calibre14">```
<?php
$router->handle('/some/route/to/handle');
```
```
### 测试路由(Testing your routes)
Since this component has no dependencies, you can create a file as shown below to test your routes:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
// These routes simulate real URIs
$testRoutes = array(
'/',
'/index',
'/index/index',
'/index/test',
'/products',
'/products/index/',
'/products/show/101',
);
$router = new Router();
// Add here your custom routes
// ...
// Testing each route
foreach ($testRoutes as $testRoute) {
// Handle the route
$router->handle($testRoute);
echo 'Testing ', $testRoute, '<br>';
// Check if some route was matched
if ($router->wasMatched()) {
echo 'Controller: ', $router->getControllerName(), '<br>';
echo 'Action: ', $router->getActionName(), '<br>';
} else {
echo 'The route wasn\'t matched by any route<br>';
}
echo '<br>';
}
```
```
### 注解路由(Annotations Router)
这个组件利用集成的注解服务 [*annotations*](#) 提供了一个路由定义的变体。通过这个策略,你可以直接在书写控制器的时候编写路由,而不需要一个一个在服务注册的时候添加。
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router\Annotations as RouterAnnotations;
$di['router'] = function () {
// Use the annotations router
$router = new RouterAnnotations(false);
// Read the annotations from ProductsController if the URI starts with /api/products
$router->addResource('Products', '/api/products');
return $router;
};
```
```
注解通过如下的方式定义:
```
<pre class="calibre14">```
<?php
/**
* @RoutePrefix("/api/products")
*/
class ProductsController
{
/**
* @Get("/")
*/
public function indexAction()
{
}
/**
* @Get("/edit/{id:[0-9]+}", name="edit-robot")
*/
public function editAction($id)
{
}
/**
* @Route("/save", methods={"POST", "PUT"}, name="save-robot")
*/
public function saveAction()
{
}
/**
* @Route("/delete/{id:[0-9]+}", methods="DELETE",
* conversors={id="MyConversors::checkId"})
*/
public function deleteAction($id)
{
}
public function infoAction($id)
{
}
}
```
```
只有标记了格式正确的注解的方法才能被用作路由。Phalcon支持如下注解:
名称描述用法RoutePrefixA prefix to be prepended to each route URI. This annotation must be placed at the class' docblock@RoutePrefix(“/api/products”)RouteThis annotation marks a method as a route. This annotation must be placed in a method docblock@Route(“/api/products/show”)GetThis annotation marks a method as a route restricting the HTTP method to GET@Get(“/api/products/search”)PostThis annotation marks a method as a route restricting the HTTP method to POST@Post(“/api/products/save”)PutThis annotation marks a method as a route restricting the HTTP method to PUT@Put(“/api/products/save”)DeleteThis annotation marks a method as a route restricting the HTTP method to DELETE@Delete(“/api/products/delete/{id}”)OptionsThis annotation marks a method as a route restricting the HTTP method to OPTIONS@Option(“/api/products/info”)用来添加路由的注解支持如下参数:
名称描述用法methodsDefine one or more HTTP method that route must meet with@Route(“/api/products”, methods={“GET”, “POST”})nameDefine a name for the route@Route(“/api/products”, name=”get-products”)pathsAn array of paths like the one passed to Phalcon\\Mvc\\Router::add@Route(“/posts/{id}/{slug}”, paths={module=”backend”})conversorsA hash of conversors to be applied to the parameters@Route(“/posts/{id}/{slug}”, conversors={id=”MyConversor::getId”})如果路由对应的控制器属于一个模块,使用 addModuleResource 效果更佳:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router\Annotations as RouterAnnotations;
$di['router'] = function () {
// Use the annotations router
$router = new RouterAnnotations(false);
// Read the annotations from Backend\Controllers\ProductsController if the URI starts with /api/products
$router->addModuleResource('backend', 'Products', '/api/products');
return $router;
};
```
```
### 注册路由实例(Registering Router instance)
You can register router during service registration with Phalcon dependency injector to make it available inside controller.
You need to add code below in your bootstrap file (for example index.php or app/config/services.php if you use [Phalcon Developer Tools](http://phalconphp.com/en/download/tools))
```
<pre class="calibre14">```
<?php
/**
* Add routing capabilities
*/
$di->set('router', function () {
require __DIR__.'/../app/config/routes.php';
return $router;
});
```
```
You need to create app/config/routes.php and add router initialization code, for example:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Router;
$router = new Router();
$router->add("/login", array(
'controller' => 'login',
'action' => 'index'
));
$router->add("/products/:action", array(
'controller' => 'products',
'action' => 1
));
return $router;
```
```
### 自定义路由(Implementing your own Router)
The [*Phalcon\\Mvc\\RouterInterface*](#) interface must be implemented to create your own router replacingthe one provided by Phalcon.
|
- [索引](# "总目录")
- [下一页](# "调度控制器(Dispatching Controllers)") |
- [上一页](# "MVC 应用(MVC Applications)") |
- API参考
- API列表
- Abstract class Phalcon\Acl
- Abstract class Phalcon\Acl\Adapter
- Class Phalcon\Acl\Adapter\Memory
- Interface Phalcon\Acl\AdapterInterface
- Class Phalcon\Acl\Exception
- Class Phalcon\Acl\Resource
- Interface Phalcon\Acl\ResourceInterface
- Class Phalcon\Acl\Role
- Interface Phalcon\Acl\RoleInterface
- Class Phalcon\Annotations\Annotation
- Abstract class Phalcon\Annotations\Adapter
- Interface Phalcon\Annotations\AdapterInterface
- Class Phalcon\Annotations\Collection
- Class Phalcon\Annotations\Exception
- Class Phalcon\Annotations\Reader
- Interface Phalcon\Annotations\ReaderInterface
- Class Phalcon\Annotations\Reflection
- Class Phalcon\Assets\Collection
- Class Phalcon\Assets\Exception
- Interface Phalcon\Assets\FilterInterface
- Class Phalcon\Assets\Filters\Cssmin
- Class Phalcon\Assets\Filters\Jsmin
- Class Phalcon\Assets\Filters\None
- Class Phalcon\Assets\Inline
- Class Phalcon\Assets\Inline\Css
- Class Phalcon\Assets\Inline\Js
- Class Phalcon\Assets\Manager
- Class Phalcon\Assets\Resource
- Class Phalcon\Assets\Resource\Css
- Class Phalcon\Assets\Resource\Js
- Abstract class Phalcon\Cache\Backend
- Class Phalcon\Cache\Backend\Apc
- Class Phalcon\Cache\Backend\File
- Class Phalcon\Cache\Backend\Libmemcached
- Class Phalcon\Cache\Backend\Memcache
- Class Phalcon\Cache\Backend\Memory
- Class Phalcon\Cache\Backend\Mongo
- Class Phalcon\Cache\Backend\Redis
- Class Phalcon\Cache\Backend\Xcache
- Interface Phalcon\Cache\BackendInterface
- Class Phalcon\Cache\Exception
- Class Phalcon\Cache\Frontend\Base64
- Class Phalcon\Cache\Frontend\Data
- Class Phalcon\Cache\Frontend\Igbinary
- Class Phalcon\Cache\Frontend\Json
- Class Phalcon\Cache\Frontend\None
- Class Phalcon\Cache\Frontend\Output
- Interface Phalcon\Cache\FrontendInterface
- Class Phalcon\Cache\Multiple
- Class Phalcon\Cli\Router\Route
- Class Phalcon\Config
- Class Phalcon\Config\Adapter\Ini
- Class Phalcon\Config\Adapter\Json
- Class Phalcon\Config\Adapter\Php
- Class Phalcon\Config\Adapter\Yaml
- Class Phalcon\Config\Exception
- Class Phalcon\Crypt
- Class Phalcon\Crypt\Exception
- Interface Phalcon\CryptInterface
- Abstract class Phalcon\Db
- Abstract class Phalcon\Db\Adapter
- Interface Phalcon\Db\AdapterInterface
- Class Phalcon\Db\Column
- Interface Phalcon\Db\ColumnInterface
- Abstract class Phalcon\Db\Dialect
- Interface Phalcon\Db\DialectInterface
- Class Phalcon\Db\Exception
- Class Phalcon\Db\Index
- Interface Phalcon\Db\IndexInterface
- Class Phalcon\Db\Profiler
- Class Phalcon\Db\RawValue
- Class Phalcon\Db\Reference
- Interface Phalcon\Db\ReferenceInterface
- Class Phalcon\Db\Result\Pdo
- Interface Phalcon\Db\ResultInterface
- Class Phalcon\Debug
- Class Phalcon\Debug\Dump
- Class Phalcon\Debug\Exception
- Interface Phalcon\DiInterface
- Abstract class Phalcon\Dispatcher
- Interface Phalcon\DispatcherInterface
- Class Phalcon\Escaper
- Class Phalcon\Escaper\Exception
- Interface Phalcon\EscaperInterface
- Class Phalcon\Events\Event
- Interface Phalcon\Events\EventsAwareInterface
- Class Phalcon\Events\Exception
- Class Phalcon\Events\Manager
- Interface Phalcon\Events\ManagerInterface
- Class Phalcon\Exception
- Class Phalcon\Filter
- Class Phalcon\Filter\Exception
- Interface Phalcon\Filter\UserFilterInterface
- Interface Phalcon\FilterInterface
- Abstract class Phalcon\Flash
- Class Phalcon\Flash\Direct
- Class Phalcon\Flash\Exception
- Class Phalcon\Flash\Session
- Interface Phalcon\FlashInterface
- Class Phalcon\Forms\Form
- Abstract class Phalcon\Forms\Element
- Class Phalcon\Forms\Exception
- Class Phalcon\Forms\Manager
- Class Phalcon\Http\Cookie
- Class Phalcon\Http\Cookie\Exception
- Class Phalcon\Http\Request
- Class Phalcon\Http\Request\Exception
- Class Phalcon\Http\Request\File
- Interface Phalcon\Http\Request\FileInterface
- Interface Phalcon\Http\RequestInterface
- Class Phalcon\Http\Response
- Class Phalcon\Http\Response\Cookies
- Interface Phalcon\Http\Response\CookiesInterface
- Class Phalcon\Http\Response\Exception
- Class Phalcon\Http\Response\Headers
- Interface Phalcon\Http\Response\HeadersInterface
- Interface Phalcon\Http\ResponseInterface
- Class Phalcon\Image
- Abstract class Phalcon\Image\Adapter
- Class Phalcon\Image\Adapter\Imagick
- Interface Phalcon\Image\AdapterInterface
- Class Phalcon\Image\Exception
- Class Phalcon\Kernel
- Class Phalcon\Loader
- Class Phalcon\Loader\Exception
- Abstract class Phalcon\Logger
- Abstract class Phalcon\Logger\Adapter
- Class Phalcon\Logger\Adapter\File
- Class Phalcon\Logger\Adapter\Firephp
- Class Phalcon\Logger\Adapter\Stream
- Class Phalcon\Logger\Adapter\Syslog
- Interface Phalcon\Logger\AdapterInterface
- Class Phalcon\Logger\Exception
- Abstract class Phalcon\Logger\Formatter
- Interface Phalcon\Logger\FormatterInterface
- Class Phalcon\Logger\Item
- Class Phalcon\Logger\Multiple
- Class Phalcon\Mvc\Application
- Class Phalcon\Mvc\Application\Exception
- Abstract class Phalcon\Mvc\Collection
- Abstract class Phalcon\Mvc\Collection\Behavior
- Class Phalcon\Mvc\Collection\Behavior\SoftDelete
- Class Phalcon\Mvc\Collection\Behavior\Timestampable
- Interface Phalcon\Mvc\Collection\BehaviorInterface
- Class Phalcon\Mvc\Collection\Document
- Class Phalcon\Mvc\Collection\Exception
- Class Phalcon\Mvc\Collection\Manager
- Interface Phalcon\Mvc\Collection\ManagerInterface
- Interface Phalcon\Mvc\CollectionInterface
- Abstract class Phalcon\Mvc\Controller
- Interface Phalcon\Mvc\ControllerInterface
- Class Phalcon\Mvc\Dispatcher
- Class Phalcon\Mvc\Dispatcher\Exception
- Interface Phalcon\Mvc\DispatcherInterface
- Interface Phalcon\Mvc\EntityInterface
- Class Phalcon\Mvc\Micro
- Class Phalcon\Mvc\Micro\Collection
- Interface Phalcon\Mvc\Micro\CollectionInterface
- Class Phalcon\Mvc\Micro\Exception
- Class Phalcon\Mvc\Micro\LazyLoader
- Interface Phalcon\Mvc\Micro\MiddlewareInterface
- Abstract class Phalcon\Mvc\Model
- Abstract class Phalcon\Mvc\Model\Behavior
- Class Phalcon\Mvc\Model\Criteria
- Interface Phalcon\Mvc\Model\CriteriaInterface
- Class Phalcon\Mvc\Model\Exception
- Class Phalcon\Mvc\Model\Manager
- Interface Phalcon\Mvc\Model\ManagerInterface
- Class Phalcon\Mvc\Model\Message
- Interface Phalcon\Mvc\Model\MessageInterface
- Abstract class Phalcon\Mvc\Model\MetaData
- Interface Phalcon\Mvc\Model\MetaDataInterface
- Class Phalcon\Mvc\Model\Query
- Interface Phalcon\Mvc\Model\QueryInterface
- Class Phalcon\Mvc\Model\Relation
- Interface Phalcon\Mvc\Model\RelationInterface
- Interface Phalcon\Mvc\Model\ResultInterface
- Abstract class Phalcon\Mvc\Model\Resultset
- Abstract class Phalcon\Mvc\Model\Validator
- Interface Phalcon\Mvc\Model\ResultsetInterface
- Class Phalcon\Mvc\Model\Row
- Class Phalcon\Mvc\Model\Transaction
- Interface Phalcon\Mvc\Model\TransactionInterface
- Class Phalcon\Mvc\Model\ValidationFailed
- Interface Phalcon\Mvc\ModelInterface
- Interface Phalcon\Mvc\ModuleDefinitionInterface
- Class Phalcon\Mvc\Router
- Class Phalcon\Mvc\Router\Annotations
- Class Phalcon\Mvc\Router\Exception
- Class Phalcon\Mvc\Router\Group
- Interface Phalcon\Mvc\Router\GroupInterface
- Class Phalcon\Mvc\Router\Route
- Interface Phalcon\Mvc\Router\RouteInterface
- Interface Phalcon\Mvc\RouterInterface
- Class Phalcon\Mvc\Url
- Class Phalcon\Mvc\Url\Exception
- Interface Phalcon\Mvc\UrlInterface
- Class Phalcon\Mvc\User\Component
- Class Phalcon\Mvc\User\Module
- Class Phalcon\Mvc\User\Plugin
- Class Phalcon\Mvc\View
- Abstract class Phalcon\Mvc\View\Engine
- Interface Phalcon\Mvc\View\EngineInterface
- Class Phalcon\Mvc\View\Exception
- Class Phalcon\Mvc\View\Simple
- Interface Phalcon\Mvc\ViewBaseInterface
- Interface Phalcon\Mvc\ViewInterface
- Abstract class Phalcon\Paginator\Adapter
- Class Phalcon\Paginator\Adapter\Model
- Class Phalcon\Paginator\Adapter\NativeArray
- Class Phalcon\Paginator\Adapter\QueryBuilder
- Interface Phalcon\Paginator\AdapterInterface
- Class Phalcon\Paginator\Exception
- Class Phalcon\Queue\Beanstalk
- Class Phalcon\Queue\Beanstalk\Job
- Final class Phalcon\Registry
- Class Phalcon\Security
- Class Phalcon\Security\Exception
- Abstract class Phalcon\Session
- Abstract class Phalcon\Session\Adapter
- Interface Phalcon\Session\AdapterInterface
- Class Phalcon\Session\Bag
- Interface Phalcon\Session\BagInterface
- Class Phalcon\Session\Exception
- Class Phalcon\Tag
- Class Phalcon\Tag\Exception
- Abstract class Phalcon\Tag\Select
- Abstract class Phalcon\Text
- Abstract class Phalcon\Translate
- Abstract class Phalcon\Translate\Adapter
- Class Phalcon\Translate\Adapter\Csv
- Class Phalcon\Translate\Adapter\Gettext
- Class Phalcon\Translate\Adapter\NativeArray
- Interface Phalcon\Translate\AdapterInterface
- Class Phalcon\Translate\Exception
- Class Phalcon\Validation
- Class Phalcon\Validation\Exception
- Class Phalcon\Validation\Message
- Class Phalcon\Validation\Message\Group
- Interface Phalcon\Validation\MessageInterface
- Abstract class Phalcon\Validation\Validator
- Class Phalcon\Validation\Validator\Alnum
- Class Phalcon\Validation\Validator\Alpha
- Class Phalcon\Validation\Validator\Between
- Class Phalcon\Validation\Validator\Confirmation
- Class Phalcon\Validation\Validator\Digit
- Class Phalcon\Validation\Validator\Email
- Class Phalcon\Validation\Validator\ExclusionIn
- Class Phalcon\Validation\Validator\File
- Class Phalcon\Validation\Validator\Identical
- Class Phalcon\Validation\Validator\InclusionIn
- Class Phalcon\Validation\Validator\Numericality
- Class Phalcon\Validation\Validator\PresenceOf
- Class Phalcon\Validation\Validator\Regex
- Class Phalcon\Validation\Validator\StringLength
- Class Phalcon\Validation\Validator\Uniqueness
- Class Phalcon\Validation\Validator\Url
- Interface Phalcon\Validation\ValidatorInterface
- Class Phalcon\Version
- 参考手册
- 安装(Installation)
- 教程 1:让我们通过例子来学习(Tutorial 1: Let’s learn by example)
- 教程 2:Introducing INVO(Tutorial 2: Introducing INVO)
- 教程 3: Securing INVO
- 教程 4: Using CRUDs
- 教程 5: Customizing INVO
- 教程 6: Vkuró
- 教程 7:创建简单的 REST API(Tutorial 7: Creating a Simple REST API)
- 示例列表(List of examples)
- 依赖注入与服务定位器(Dependency Injection/Service Location)
- MVC 架构(The MVC Architecture)
- 使用控制器(Using Controllers)
- 使用模型(Working with Models)
- 模型元数据(Models Meta-Data)
- 事务管理(Model Transactions)
- Phalcon 查询语言(Phalcon Query Language (PHQL))
- 缓存对象关系映射(Caching in the ORM)
- 对象文档映射 ODM (Object-Document Mapper)
- 使用视图(Using Views)
- 视图助手(View Helpers)
- 资源文件管理(Assets Management)
- Volt 模版引擎(Volt: Template Engine)
- MVC 应用(MVC Applications)
- 路由(Routing)
- 调度控制器(Dispatching Controllers)
- 微应用(Micro Applications)
- 使用命名空间(Working with Namespaces)
- 事件管理器(Events Manager)
- Request Environment
- 返回响应(Returning Responses)
- Cookie 管理(Cookies Management)
- 生成 URL 和 路径(Generating URLs and Paths)
- 闪存消息(Flashing Messages)
- 使用 Session 存储数据(Storing data in Session)
- 过滤与清理(Filtering and Sanitizing)
- 上下文编码(Contextual Escaping)
- 验证(Validation)
- 表单(Forms)
- 读取配置(Reading Configurations)
- 分页(Pagination)
- 使用缓存提高性能(Improving Performance with Cache)
- 安全(Security)
- Encryption/Decryption
- 访问控制列表 ACL(Access Control Lists ACL)
- 多语言支持(Multi-lingual Support)
- Universal Class Loader
- 日志记录(Logging)
- 注释解析器(Annotations Parser)
- 命令行应用(Command Line Applications)
- 队列(Queueing)
- 数据库抽象层(Database Abstraction Layer)
- 国际化(Internationalization)
- 数据库迁移(Database Migrations)
- 调试应用程序(Debugging Applications)
- Phalcon 开发工具(Phalcon Developer Tools)
- 提高性能:下一步该做什么?(Increasing Performance: What’s next?)
- 单元测试(Unit testing)
- 授权(License)