controller.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. if ( ! defined('BASE_PATH')) exit('No direct script access allowed');
  3. class controller{
  4. public $content_type;
  5. public $succeed ;
  6. public $error_type;
  7. public function __construct($request = ''){
  8. $this->content_type = 'text/plain';
  9. $this->error_type = 0;
  10. $this->succeed = TRUE;
  11. $request = ltrim($request,'/');
  12. //是否为SAE环境
  13. if(!IS_SAE || !class_exists('SaeStorage')){//
  14. $this->error_type = 2;
  15. $this->succeed = FALSE;
  16. }
  17. //请求为空
  18. elseif($request === ''){
  19. //显示欢迎页面
  20. if(WELCOME_DOC){
  21. view::show('welcome');
  22. return ;
  23. }else{
  24. $this->error_type = 1;
  25. $this->succeed = FALSE;
  26. }
  27. }
  28. else{
  29. //匹配文件后缀
  30. $temp = array();
  31. if(preg_match('/\.(jpg|jpeg|png|pdf|gif|css|js|zip)$/i', $request,$temp)===1){//暂时先就这几种
  32. //http://en.wikipedia.org/wiki/Internet_media_type#List_of_common_media_types
  33. switch($temp[1]){
  34. case 'jpg':{$this->content_type="image/jpeg";}break;
  35. case 'gif':{$this->content_type="image/gif";}break;
  36. case 'png':{$this->content_type="image/png";}break;
  37. case 'css':{$this->content_type="text/css";}break;
  38. case 'js':{$this->content_type="text/javascript";}break;
  39. }
  40. }
  41. }
  42. //开始处理
  43. $this->handle($request);
  44. }
  45. /**
  46. * 获取内容并输出
  47. * 如果stroage里面不存在,则从URL里面获取
  48. * */
  49. private function handle($filename){
  50. $content = '';
  51. if($this->succeed){
  52. $storage = new storage();
  53. if($storage->exists($filename)){
  54. $content = $storage->read($filename);
  55. }else{
  56. $content = @file_get_contents(BASE_URL.$filename);
  57. $storage->write($filename, $content);
  58. }
  59. if(empty($content)){
  60. $this->error_type = 3;
  61. $this->succeed = FALSE;
  62. }
  63. }
  64. //显示内容
  65. $this->render($content);
  66. }
  67. /**
  68. * 输出结果,包括缓存控制等
  69. * */
  70. private function render($content=''){
  71. if(!$this->succeed){
  72. $this->error();
  73. return ;
  74. }else{
  75. header("Expires: " . date("D, j M Y H:i:s GMT", time()+2592000));//缓存一月
  76. header('Content-type: '.$this->content_type);
  77. echo $content;
  78. }
  79. }
  80. /**
  81. * 处理错误
  82. * */
  83. private function error(){
  84. echo "<strong>something seems wrong.</strong>";
  85. }
  86. }