Yii2.0 路由

来源:互联网 发布:吕鑫c语言 编辑:程序博客网 时间:2024/06/05 03:06

存放位置:在config目录文件下新建一个routes.php文件作为主路由文件

继承自谁:

use yii\helpers\Url;//注意继承大写// Url::to() calls UrlManager::createUrl() to create a URL调用UrlManager方法生成url;$url = Url::to(['post/view', 'id' => 100]);访问方式:/index.php?r=post%2Fview&id=100/index.php/post/100/posts/100

前面的URL地址:

http://127.0.0.1/yii2.0/basic/web/index.php?r=site/say&message=Hello+ppp

注释:
r参数:路由控制器文件控制的;
r=模块控制器/动作&传递的参数=值;

例如上面的URL的意思是
访问site控制器下的say动作方法并传递参数message;

缺省路由

如果传入请求并没有提供一个具体的路由,(一般这种情况多为于对首页的请求)此时就会启用由 yii\web\Application::defaultRoute 属性所指定的缺省路由。 该属性的默认值为 site/index,
它指向 site 控制器的 index 操作
。你可以像这样在应用配置中调整该属性的值:

return [
// …
‘defaultRoute’ => ‘main/index’,
];

catchAll 路由(全拦截路由)

有时候,你会想要将你的 Web 应用临时调整到维护模式,所有的请求下都会显示相同的信息页。当然,要实现这一点有很多种方法。这里面最简单快捷的方法就是在应用配置中设置下 yii\web\Application::catchAll 属性:

return [
// …
‘catchAll’ => [‘site/offline’],
];

路由生成url的几种方式

//跳转时可以用到use yii\helpers\Url;// creates a URL to a route: /index.php?r=post%2Findexecho Url::to(['post/index']);// creates a URL to a route with parameters: /index.php?r=post%2Fview&id=100echo Url::to(['post/view', 'id' => 100]);// creates an anchored URL: /index.php?r=post%2Fview&id=100#contentecho Url::to(['post/view', 'id' => 100, '#' => 'content']);// creates an absolute URL: http://www.example.com/index.php?r=post%2Findexecho Url::to(['post/index'], true);// creates an absolute URL using the https scheme: https://www.example.com/index.php?r=post%2Findexecho Url::to(['post/index'], 'https');路由反向代理获取静态资源,如图片、css、js、等:use yii\helpers\Url;// currently requested URL: /index.php?r=admin%2Fpost%2Findexecho Url::to();// an aliased URL: http://example.comYii::setAlias('@example', 'http://example.com/');echo Url::to('@example');// an absolute URL: http://example.com/images/logo.gifecho Url::to('/images/logo.gif', true);路由的其他方法:use yii\helpers\Url;// home page URL: /index.php?r=site%2Findexecho Url::home();// the base URL, useful if the application is deployed in a sub-folder of the Web rootecho Url::base();// the canonical URL of the currently requested URL// see https://en.wikipedia.org/wiki/Canonical_link_elementecho Url::canonical();// remember the currently requested URL and retrieve it back in later requestsUrl::remember();echo Url::previous();路由美化、配置方法:[    'components' => [        'urlManager' => [            'enablePrettyUrl' => true,            'showScriptName' => false,            'enableStrictParsing' => false,            'rules' => [                // ...            ],        ],    ],]正则匹配:[    'posts' => 'post/index',     'post/<id:\d+>' => 'post/view',][    // ...other url rules...    [        'pattern' => 'posts',        'route' => 'post/index',        'suffix' => '.json',    ],][    'posts/<year:\d{4}>/<category>' => 'post/index',    'posts' => 'post/index',    'post/<id:\d+>' => 'post/view',]
0 0