首页 > 开发 > PHP > 正文

Symfony2学习笔记之系统路由详解

2024-05-04 22:31:47
字体:
来源:转载
供稿:网友

本文详细讲述了Symfony2的系统路由。分享给大家供大家参考,具体如下:

漂亮的URL绝对是一个严肃的web应用程序必须做到的,这种方式使index.php?article_id=57这类的丑陋URL被隐藏,由更受欢迎的像 /read/intro-to-symfony 来替代。

拥有灵活性更为重要,如果你要改变一个页面的URL,比如从/blog 到 /new 怎么办?

有多少链接需要你找出来并更新呢? 如果你使用Symfony的router,这种改变将变得很简单。

Symfony2 router让你定义更具创造力的URL,你可以map你的应用程序的不同区域。

创建复杂的路由并map到controllers并可以在模板和controllers内部生成URLs

从bundles(或者其他任何地方)加载路由资源

调试你的路由

路由活动

一个路径是一个从URL 模式到一个controller的绑定。

比如假设你想匹配任何像 /blog/my-post 或者 /blog/all-about-symfony的路径并把它们发送到一个controller在那里可以查找并渲染blog实体。

该路径很简单:

YAML格式:

# app/config/routing.ymlblog_show:pattern: /blog/{slug}defaults: {_controller: AcmeBlogBundle:Blog:show }

XML格式:

<!-- app/config/routing.xml --><?xml version="1.0" encoding="UTF-8" ?><routes xmlns="http://symfony.com/schema/routing"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"><route id="blog_show" pattern="/blog/{slug}"><default key="_controller">AcmeBlogBundle:Blog:show</default></route></routes>

PHP代码格式:

// app/config/routing.phpuse Symfony/Component/Routing/RouteCollection;use Symfony/Component/Routing/Route;$collection = new RouteCollection();$collection->add('blog_show', new Route('/blog/{slug}', array(     '_controller' => 'AcmeBlogBundle:Blog:show',)));

blog_show路径定义了一个URL模式,它像/blog/* 这里的通配符被命名为slug。对于URL/blog/my-blog-post,slug变量会得到值 my-blog-post。
_controller参数是一个特定的键,它告诉Symfogy当一个URL匹配这个路径时哪个controller将要被执行。
_controller字符串被称为逻辑名。它的值会按照特定的模式来指定具体的PHP类和方法。

// src/Acme/BlogBundle/Controller/BlogController.phpnamespace Acme/BlogBundle/Controller;use Symfony/Bundle/FrameworkBundle/Controller/Controller;class BlogController extends Controller{  public function showAction($slug)  {    $blog = // use the $slug variable to query the database    return $this->render('AcmeBlogBundle:Blog:show.html.twig', array(      'blog' => $blog,    ));  }}

现在当你再访问/blog/my-post 时,showAction controller将被执行并且$slug变量的值为my-post

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表