1、nginx代理:
當webman需要直接提供外網通路時,建議在webman前增加一個nginx代理,這樣有以下好處。
- 靜态資源由nginx處理,讓webman專注業務邏輯處理
- 讓多個webman共用80、443端口,通過域名區分不同站點,實作單台伺服器部署多個站點
- 能夠實作php-fpm與webman架構共存
- nginx代理ssl實作https,更加簡單高效
- 能夠嚴格過濾外網一些不合法請求
// nginx代理示例
upstream webman {
server 127.0.0.1:8787;
keepalive 10240;
}
server {
server_name 站點域名;
listen 80;
access_log off;
root /your/webman/public;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Connection "";
if (!-f $request_filename){
proxy_pass http://webman;
}
}
}
2、簡單示例:
// 傳回字元串
// 建立控制器
// 建立檔案 app/controller/UserController.php 如下
<?php
namespace app\controller;
use support\Request;
class UserController
{
public function hello(Request $request)
{
$default_name = 'webman';
// 從get請求裡獲得name參數,如果沒有傳遞name參數則傳回$default_name
$name = $request->get('name', $default_name);
// 向浏覽器傳回字元串
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助手函數傳回資料将自動加上一個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/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 -->
<!-- 将傳回一個内容為 hello tom 的html頁面 -->
<!-- 注意:webman預設使用的是php原生文法作為模版 -->