webman快速上手簡(jiǎn)單示例
返回字符串
新建控制器
新建文件 app/controller/UserController.php
如下
<?php
namespace app\controller;
use support\Request;
class UserController
{
public function hello(Request $request)
{
$default_name = 'webman';
// 從get請(qǐng)求里獲得name參數(shù),如果沒有傳遞name參數(shù)則返回$default_name
$name = $request->get('name', $default_name);
// 向?yàn)g覽器返回字符串
return response('hello ' . $name);
}
}
訪問
在瀏覽器里訪問 http://127.0.0.1:8787/user/hello?name=tom
瀏覽器將返回 hello tom
返回json
更改文件 app/controller/UserController.php
如下
<?php
namespace app\controller;
use support\Request;
class UserController
{
public function hello(Request $request)
{
$default_name = 'webman';
$name = $request->get('name', $default_name);
return json([
'code' => 0,
'msg' => 'ok',
'data' => $name
]);
}
}
訪問
在瀏覽器里訪問 http://127.0.0.1:8787/user/hello?name=tom
瀏覽器將返回 {"code":0,"msg":"ok","data":"tom""}
使用json助手函數(shù)返回?cái)?shù)據(jù)將自動(dòng)加上一個(gè)header頭 Content-Type: application/json
返回xml
同理,使用助手函數(shù) xml($xml)
將返回一個(gè)帶 Content-Type: text/xml
頭的xml
響應(yīng)。
其中$xml
參數(shù)可以是xml
字符串,也可以是SimpleXMLElement
對(duì)象
返回jsonp
同理,使用助手函數(shù) jsonp($data, $callback_name = 'callback')
將返回一個(gè)jsonp
響應(yīng)。
返回視圖
更改文件 app/controller/UserController.php
如下
<?php
namespace app\controller;
use support\Request;
class UserController
{
public function hello(Request $request)
{
$default_name = 'webman';
$name = $request->get('name', $default_name);
return view('user/hello', ['name' => $name]);
}
}
新建文件 app/view/user/hello.html
如下
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>webman</title>
</head>
<body>
hello <?=htmlspecialchars($name)?>
</body>
</html>
在瀏覽器里訪問 http://127.0.0.1:8787/user/hello?name=tom
將返回一個(gè)內(nèi)容為 hello tom
的html頁(yè)面。
注意:webman默認(rèn)使用的是php原生語法作為模版。如果想使用其它視圖參見視圖。