webmanのクイックスタート簡単な例
文字列を返す
コントローラーを新規作成
ファイル 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ヘルパー関数を使用してデータを返すと、自動的に 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のネイティブ構文をテンプレートとして使用します。他のビューを使用したい場合はビューを参照してください。