View.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace daswork\response;
  3. use daswork\Config;
  4. use daswork\Response;
  5. use daswork\View as ViewTemplate;
  6. class View extends Response
  7. {
  8. // 输出参数
  9. protected $options = [];
  10. protected $vars = [];
  11. protected $replace = [];
  12. protected $contentType = 'text/html';
  13. /**
  14. * 处理数据
  15. * @access protected
  16. * @param mixed $data 要处理的数据
  17. * @return mixed
  18. */
  19. protected function output($data)
  20. {
  21. // 渲染模板输出
  22. return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
  23. ->fetch($data, $this->vars, $this->replace);
  24. }
  25. /**
  26. * 获取视图变量
  27. * @access public
  28. * @param string $name 模板变量
  29. * @return mixed
  30. */
  31. public function getVars($name = null)
  32. {
  33. if (is_null($name)) {
  34. return $this->vars;
  35. } else {
  36. return isset($this->vars[$name]) ? $this->vars[$name] : null;
  37. }
  38. }
  39. /**
  40. * 模板变量赋值
  41. * @access public
  42. * @param mixed $name 变量名
  43. * @param mixed $value 变量值
  44. * @return $this
  45. */
  46. public function assign($name, $value = '')
  47. {
  48. if (is_array($name)) {
  49. $this->vars = array_merge($this->vars, $name);
  50. return $this;
  51. } else {
  52. $this->vars[$name] = $value;
  53. }
  54. return $this;
  55. }
  56. /**
  57. * 视图内容替换
  58. * @access public
  59. * @param string|array $content 被替换内容(支持批量替换)
  60. * @param string $replace 替换内容
  61. * @return $this
  62. */
  63. public function replace($content, $replace = '')
  64. {
  65. if (is_array($content)) {
  66. $this->replace = array_merge($this->replace, $content);
  67. } else {
  68. $this->replace[$content] = $replace;
  69. }
  70. return $this;
  71. }
  72. }