## 重定向
可以使用`redirect`助手函數進行重定向
~~~
<?php
namespace app\index\controller;
class Index
{
public function hello()
{
return redirect('http://www.thinkphp.cn');
}
}
~~~
> `redirect`函數和控制器的`redirect`方法的參數順序有所區別
### 重定向傳參
如果是站內重定向的話,可以支持URL組裝,有兩種方式組裝URL,第一種是直接使用完整地址(`/`打頭)
~~~
redirect('/index/index/hello/name/thinkphp');
~~~
這種方式會保持原來地址不做任何轉換,第二種方式是使用`params`方法配合,例如:
~~~
redirect('hello')->params(['name'=>'thinkphp']);
~~~
最終重定向的URL地址和前面的一樣的,系統內部會自動判斷并調用`url`(用于快速生成URL地址的助手函數)方法進行地址生成,或者使用下面的方法
~~~
redirect('hello',['name'=>'thinkphp']);
~~~
還可以支持使用`with`方法附加`Session`閃存數據重定向。
~~~
<?php
namespace app\index\controller;
class Index
{
public function index()
{
return redirect('hello')->with('name','thinkphp');
}
public function hello()
{
$name = session('name');
return 'hello,'.$name.'!';
}
}
~~~
從示例可以看到重定向隱式傳值使用的是`Session`閃存數據隱式傳值,并且**僅在下一次請求有效**,再次訪問重定向地址的時候無效。
### 記住請求地址
在很多時候,我們重定向的時候需要記住當前請求地址(為了便于跳轉回來),我們可以使用`remember`方法記住重定向之前的請求地址。
下面是一個示例,我們第一次訪問`index`操作的時候會重定向到`hello`操作并記住當前請求地址,然后操作完成后到`restore`方法,`restore`方法則會自動重定向到之前記住的請求地址,完成一次重定向的回歸,回到原點!(再次刷新頁面又可以繼續執行)
~~~
<?php
namespace app\index\controller;
class Index
{
public function index()
{
// 判斷session完成標記是否存在
if (session('?complete')) {
// 刪除session
session('complete', null);
return '重定向完成,回到原點!';
} else {
// 記住當前地址并重定向
return redirect('hello')
->with('name', 'thinkphp')
->remember();
}
}
public function hello()
{
$name = session('name');
return 'hello,' . $name . '! <br/><a href="/index/index/restore">點擊回到來源地址</a>';
}
public function restore()
{
// 設置session標記完成
session('complete', true);
// 跳回之前的來源地址
return redirect()->restore();
}
}
~~~
點贊