webman เริ่มต้นอย่างรวดเร็ว ตัวอย่างง่าย

คืนค่าสตริง

สร้างตัวควบคุมใหม่

สร้างไฟล์ app/controller/UserController.php ดังนี้

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        $default_name = 'webman';
        // ดึงค่า parameter name จาก request แบบ get ถ้าไม่มีการส่งค่า 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) จะคืนค่าการตอบสนอง xml ที่มี header เป็น Content-Type: text/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
จะคืนค่าเป็นหน้า html ที่มีเนื้อหา hello tom

หมายเหตุ: webman ใช้ไวยากรณ์ php ดั้งเดิมเป็นเทมเพลตโดยค่าเริ่มต้น ถ้าต้องการใช้มุมมองอื่นสามารถดูได้ที่ มุมมอง