简单示例

返回字符串

新建控制器

新建文件 app/controller/User.php 如下

  1. <?php
  2. namespace app\controller;
  3. use support\Request;
  4. class User
  5. {
  6. public function hello(Request $request)
  7. {
  8. $default_name = 'webman';
  9. // 从get请求里获得name参数,如果没有传递name参数则返回$default_name
  10. $name = $request->get('name', $default_name);
  11. // 向浏览器返回字符串
  12. return response('hello ' . $name);
  13. }
  14. }

访问

在浏览器里访问 http://127.0.0.1:8787/user/hello?name=tom

浏览器将返回 hello tom

返回json

更改文件 app/controller/User.php 如下

  1. <?php
  2. namespace app\controller;
  3. use support\Request;
  4. class User
  5. {
  6. public function hello(Request $request)
  7. {
  8. $default_name = 'webman';
  9. $name = $request->get('name', $default_name);
  10. return json([
  11. 'code' => 0,
  12. 'msg' => 'ok',
  13. 'data' => $name
  14. ]);
  15. }
  16. }

访问

在浏览器里访问 http://127.0.0.1:8787/user/hello?name=tom

浏览器将返回 {"code":0,"msg":"ok","data":"tom""}

使用json助手函数返回数据将自动加上一个header头 Content-Type: application/json

返回xml

同理,使用助手函数 xml($xml) 将返回一个带 Content-Type: text/xml 头的xml响应。

其中$xml参数可以是xml字符串,也可以是SimpleXMLElement对象

返回jsonp

同理,使用助手函数 jsonp($data, $callback_name = 'callback') 将返回一个jsonp响应。

返回视图

更改文件 app/controller/User.php 如下

  1. <?php
  2. namespace app\controller;
  3. use support\Request;
  4. class User
  5. {
  6. public function hello(Request $request)
  7. {
  8. $default_name = 'webman';
  9. $name = $request->get('name', $default_name);
  10. return view('user/hello', ['name' => $name]);
  11. }
  12. }

新建文件 app/view/user/hello.html 如下

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>webman</title>
  6. </head>
  7. <body>
  8. hello <?=htmlspecialchars($name)?>
  9. </body>
  10. </html>

在浏览器里访问 http://127.0.0.1:8787/user/hello?name=tom 将返回一个内容为 hello tom 的html页面。

注意:webman默认使用的是php原生语法作为模版。如果想使用其它视图参见视图