Redirect.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\response;
  12. use think\Request;
  13. use think\Response;
  14. use think\Session;
  15. use think\Url;
  16. class Redirect extends Response
  17. {
  18. protected $options = [];
  19. // URL参数
  20. protected $params = [];
  21. public function __construct($data = '', $code = 302, array $header = [], array $options = [])
  22. {
  23. parent::__construct($data, $code, $header, $options);
  24. $this->cacheControl('no-cache,must-revalidate');
  25. }
  26. /**
  27. * 处理数据
  28. * @access protected
  29. * @param mixed $data 要处理的数据
  30. * @return mixed
  31. */
  32. protected function output($data)
  33. {
  34. $this->header['Location'] = $this->getTargetUrl();
  35. return;
  36. }
  37. /**
  38. * 重定向传值(通过Session)
  39. * @access protected
  40. * @param string|array $name 变量名或者数组
  41. * @param mixed $value 值
  42. * @return $this
  43. */
  44. public function with($name, $value = null)
  45. {
  46. if (is_array($name)) {
  47. foreach ($name as $key => $val) {
  48. Session::flash($key, $val);
  49. }
  50. } else {
  51. Session::flash($name, $value);
  52. }
  53. return $this;
  54. }
  55. /**
  56. * 获取跳转地址
  57. * @return string
  58. */
  59. public function getTargetUrl()
  60. {
  61. return strpos($this->data, '://') ? $this->data : Url::build($this->data, $this->params);
  62. }
  63. public function params($params = [])
  64. {
  65. $this->params = $params;
  66. return $this;
  67. }
  68. /**
  69. * 记住当前url后跳转
  70. * @return $this
  71. */
  72. public function remember()
  73. {
  74. Session::set('redirect_url', Request::instance()->url());
  75. return $this;
  76. }
  77. /**
  78. * 跳转到上次记住的url
  79. * @return $this
  80. */
  81. public function restore()
  82. {
  83. if (Session::has('redirect_url')) {
  84. $this->data = Session::get('redirect_url');
  85. Session::delete('redirect_url');
  86. }
  87. return $this;
  88. }
  89. }