Blogger Information
Blog 37
fans 1
comment 0
visits 32497
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
控制器访问与参数解析类以及api天气接口实现输入城市查询天气
Jason Pu?
Original
654 people have browsed it

一.控制器访问与参数解析类

已知有一个控制器类如下:

  1. class UserController
  2. {
  3. public function show($id,$name)
  4. {
  5. return 'Hello '.$name . ', id = ' . $id;
  6. }
  7. }

如果需要用url参数调用这个类,我们一般会使用

  1. http://www.test.com/Controller.php?user=show&id=10&name=admin”

,这种URL对于搜索引擎非常不友好的。很多搜索引擎收录的时候,都会忽略Query String之后的内容,为此我们需要写一个类从url的pathinfo中解析出控制器和方法

  1. //目标:将URL中的控制器和方法以及参数解析出来
  2. class GetControllerInfo
  3. {
  4. public $pathinfo;
  5. public function __construct($original_path_info)
  6. {
  7. $this->pathinfo = array_filter(explode('/', $original_path_info));
  8. }
  9. //解析控制器
  10. public function getController()
  11. {
  12. return ucfirst($this->pathinfo[1]) . "Controller";
  13. }
  14. //解析控制器中的方法名称
  15. public function getMethod()
  16. {
  17. return $this->pathinfo[2];
  18. }
  19. //解析参数
  20. public function getParameters()
  21. {
  22. $params_array = [];
  23. $params = array_slice($this->pathinfo, 2);
  24. for ($i = 0; $i < count($params); $i += 2) {
  25. if (isset($params[$i + 1])) {
  26. $params_array[$params[$i]] = $params[$i + 1];
  27. }
  28. }
  29. return $params_array;
  30. }
  31. }

使用url:

  1. http://localhost:3000/0305homework/Controller.php/user/show/id/10/name/admin

在Controller页面引入解析类:

  1. require 'parameter_parse.php';
  2. $userparameter = new GetControllerInfo($_SERVER['PATH_INFO']);
  3. $controller = $userparameter->getController();
  4. $method = $userparameter->getMethod();
  5. $parameter = $userparameter->getParameters();
  6. // echo $parameter;
  7. // var_dump($controller);
  8. // var_dump($method);
  9. // var_dump($parameter);
  10. // 请求数据:http://localhost:3000/0305homework/Controller.php/user/show/id/10/name/admin
  11. echo call_user_func_array([(new $controller),$method],$parameter);

实验结果:


二.利用api让用户输入城市并显示天气预报

1.html部分:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <form action="" method="get">
  11. 输入所在城市:<input type="text" name="city" >
  12. <input type="submit">
  13. </form>
  14. <div class="show">
  15. <table border="1">
  16. <thead>所在城市天气预报</thead>
  17. <tbody>
  18. <tr>
  19. <th>所在城市</th>
  20. <th>当前温度</th>
  21. <th>当前湿度</th>
  22. <th>当前天气</th>
  23. <th>当前风向</th>
  24. <th>当前风力</th>
  25. <th>当前空气质量</th>
  26. </tr>
  27. <tr>
  28. <td><?=$data['city']?></td>
  29. <td><?=$data["realtime"]["temperature"]?></td>
  30. <td><?=$data["realtime"]["humidity"]?></td>
  31. <td><?=$data["realtime"]["info"]?></td>
  32. <td><?=$data["realtime"]["direct"]?></td>
  33. <td><?=$data["realtime"]["power"]?></td>
  34. <td><?=$data["realtime"]["aqi"]?></td>
  35. </tr>
  36. </tbody>
  37. </table>
  38. </div>
  39. </body>
  40. </html>

php部分:

  1. <?php
  2. header('content-type:text/html;charset=utf-8');
  3. header('Access-Control-Allow-Origin:*');
  4. // 请求的接口URL
  5. $apiUrl = 'http://apis.juhe.cn/simpleWeather/query';
  6. // 请求参数
  7. $params = [
  8. 'city' => $_GET['city'], // 要查询的城市
  9. 'key' => '43ecc4a52161a4d8c176f3087f79786c'
  10. ];
  11. $paramsString = http_build_query($params);
  12. // 发起接口网络请求
  13. $response = juheHttpRequest($apiUrl, $paramsString , 1);
  14. $result = json_decode($response, true);
  15. if ($result) {
  16. $errorCode = $result['error_code'];
  17. if ($errorCode == 0) {
  18. // 获取返回的天气相关信息,具体根据业务实际逻辑调整修改
  19. $data = $result['result'];
  20. } else {
  21. // 请求异常
  22. echo "请求异常:{$errorCode}_{$result["reason"]}".PHP_EOL;
  23. // echo json_encode("请求异常:{$errorCode}_{$result["reason"]}");
  24. // echo "callback(".$data.")";
  25. }
  26. } else {
  27. // 可能网络异常等问题,无法正常获得相应内容,业务逻辑可自行修改
  28. echo "请求异常".PHP_EOL;
  29. }
  30. /**
  31. * 发起网络请求函数
  32. * @param $url 请求的URL
  33. * @param bool $params 请求的参数内容
  34. * @param int $ispost 是否POST请求
  35. * @return bool|string 返回内容
  36. */
  37. function juheHttpRequest($url, $params = false, $ispost = 0)
  38. {
  39. $httpInfo = array();
  40. $ch = curl_init();
  41. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  42. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
  43. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
  44. curl_setopt($ch, CURLOPT_TIMEOUT, 12);
  45. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  46. if ($ispost) {
  47. curl_setopt($ch, CURLOPT_POST, true);
  48. curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  49. curl_setopt($ch, CURLOPT_URL, $url);
  50. } else {
  51. if ($params) {
  52. curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
  53. } else {
  54. curl_setopt($ch, CURLOPT_URL, $url);
  55. }
  56. }
  57. $response = curl_exec($ch);
  58. if ($response === FALSE) {
  59. // echo "cURL Error: ".curl_error($ch);
  60. return false;
  61. }
  62. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  63. $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
  64. curl_close($ch);
  65. return $response;
  66. }
  67. ?>

随机输入一个城市名测试:

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:代码很清晰,不错嘛
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post