thinkphp5.1使用Route路由

一、开启路由

thinkphp的路由一般默认都是开启的,如果没有开启,可以在config.php里添加如下配置:

'url_route_on' => true, //开启路由
'url_route_must' => true,//表示强制开启路由,必须定义路由才能访问。一般都是使用false,即混合模式,不用路由也可以访问

二、添加路由规则

1、首先在application\index\controller\Index.php添加一个hello的方法,如下:

<?php
namespace app\index\controller;
class Index
{
    public function index()
    {
        return view();
    }
	
    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }
}

2、在route/route.php或者application\route.php添加路由规则,如下:

<?php
/*--------------------------------------------
* 添加路由规则:
* 1、路由到index控制器的hello操作方法
* 2、浏览器访问:http://域名/hello/参数
* -------------------------------------------*/
//方式一(在:name外面添加[],表示路由参数name为可选):
Route::get('hello/[:name]', 'index/hello');
//方式二:
return [
    'hello/[:name]' => 'index/hello',
];

 3、定义路由的请求类型和后缀

return [
  // 定义路由的请求类型和后缀
  'hello/[:name]' => ['index/hello', ['method' => 'get', 'ext' => 'do']],
];

定义后缀后,必须添加后缀才能访问,如下:

 

三、添加路由别名

方式一:

动态方法:Route::alias('规则名称','模块/控制器',[路由参数]);

/*--------------------------------------------
* 添加路由别名:
* 1、别名路由到 分组/控制器名
* 2、浏览器访问:http://域名/别名
* -------------------------------------------*/
Route::alias('index','index/Index');
Route::alias('login','index/Login');
Route::alias('main','index/Main');
/*--------------------------------------------

方式二:

动态数组:return[

      '__alias__'=>['规则名称','模块/控制器',[路由参数]]

];

return [
    //路由别名
    '__alias__' =>  [
       'index'  =>  'index/Index',
       'login'=> 'index/Login',
       'main'=> 'index/Main',
    ],
];

四、添加路由分组

1、在application\index\controller\Index.php添加如下几个方法,如下:

<?php
namespace app\index\controller;

class Index
{
	public function get($id)
	{
		return '获取id=' . $id . '的内容';
	}
	
	public function read($name)
	{
		return '查看name=' . $name . '的内容';
	}
	
	public function find($year, $month)
	{
		return '查看' . $year . '年' . $month . '月的内容';
	}
}

2、在route/route.php或者application\route.php添加路由分组规则,如下:

<?php
return [
	//路由分组(按顺序匹配)
	'[index]' => [	
		':year/:month' => ['index/find', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']],	 
		':id'     => ['index/get', ['method' => 'get'], ['id' => '\d+']],
		':name'    => ['index/read', ['method' => 'get'], ['name' => '\w+']],	 
	],
];

3、浏览器访问,效果如下图:

五、thinkphp访问路由报错“No input file specified.”的解决方法:

修改伪静态配置文件.htaccess,打开htaccess文件,在index.php之后添加?(问号),如下:

<IfModule mod_rewrite.c>
 Options +FollowSymlinks -Multiviews
  RewriteEngine On
  RewriteCond $1 !^(index.php|images|robots.txt)
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值