Redirect.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 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. if (strpos($this->data, '://') || (0 === strpos($this->data, '/') && empty($this->params))) {
  62. return $this->data;
  63. } else {
  64. return Url::build($this->data, $this->params);
  65. }
  66. }
  67. public function params($params = [])
  68. {
  69. $this->params = $params;
  70. return $this;
  71. }
  72. /**
  73. * 记住当前url后跳转
  74. * @return $this
  75. */
  76. public function remember()
  77. {
  78. Session::set('redirect_url', Request::instance()->url());
  79. return $this;
  80. }
  81. /**
  82. * 跳转到上次记住的url
  83. * @return $this
  84. */
  85. public function restore()
  86. {
  87. if (Session::has('redirect_url')) {
  88. $this->data = Session::get('redirect_url');
  89. Session::delete('redirect_url');
  90. }
  91. return $this;
  92. }
  93. }