輸入輸出與視圖 - kouji6309/SingleMVC GitHub Wiki
使用 SingleMVC 取得輸入資料的方法有兩種,一是 進入點 的參數,另一個是 input 函數。輸出基本上只有 output 函數。當然,原始的 $_GET 、$_POST、 echo 等依然還是可用的。
注意 input 函數的行為:若在框架執行後(如控制器或模組內)修改 $_GET
、$_POST
、$_FILES
等變數,並不會影響傳回結果。
當路由改寫完後,會執行進入點,並帶入參數,此時可以從進入點的參數取得資料。例如請求是 http://example.com/home/news/6/4002
, 執行後 $type
和 $id
可得到資料 6
和 4002
public function news($type = -1, $id = -1) {
if ($type != -1 && $id != -1) {
// 做點什麼
}
}
input 函數有多種用法,例如執行
http://example.com/home/search?q=搜尋內容&c[]=1&c[]=2&f[p]=1&f[M]=100
public function search() {
$q = input('q'); // 得到 '搜尋內容'
$c = input('c'); // 得到 ['1', '2']
$f_M = input(['f', 'M']); // 得到 '100'
$get = input(); // 得到 ['q' => '搜尋內容', 'c' => ['1', '2'],
// 'f' => ['p' => '1', 'M' => '100']]
$get2 = input('get'); // 同上
// 做點什麼
}
當然兩者可以同時使用,例如對 http://example.com/homes/message/10?cid=503
POST 資料 title=標題&message=訊息內容
public function message_post($id = -1) {
$info = [
'id' => $id, // 得到 '10'
'title' => input('title'), // 得到 '標題'
'message' => input('message'), // 得到 '訊息內容'
'cid' => input('cid', 'get'), // 得到網址的 '503'
];
// 做點什麼
}
output 函數主要用於最後的輸出,或是輸出多的 View,因此通常是
public function news() {
// 做點什麼
output('header');
output('content/news', $data);
output('footer');
}
public function login_post() {
// 做點什麼
output('json', [
'status' => 0,
'message' => 'OK'
]);
}
另外可以在 View 中再次使用 output
另一個 View,前次呼叫的資料會自動帶入下一個 View 中。
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php output('content/'.$page); ?>
</body>
</html>
扣除直接用 output
輸出 HTML 外,建立 View 的方式有兩種,一是在 views
資料夾下建立檔案(分離檔案結構),使用時直接用 views
下的路定當作 View 名稱即可,例如 output('header.php')
、 output('content/news.php')
或不加副檔名如 output('content/product')
source
└ views
├ content
│ ├ news.php
│ └ product.php
├ header.php
├ footer.php
└ ...
另一是寫在 PHP 中(單一檔案結構),使用時指定 key
來讀取,例如 output('content-news')
<?php
require 'SingleMVC.php';
SingleMVC::$view['content-news'] = '
<?php foreach ($data as $d): ?>
<div id="news">
<h3><?=$d["titile"]?></h3>
<div><?=$d["message"]?></div>
</div>
<?php endforeach; ?>
';
class welcome extends Controller {
public function index() {
$news = [['title' => '標題', 'message' => '內容']];
output('content-news', ['data' => $news]);
}
}
若有用到多語系,會搭配 lang 讀取語系資料,可看這裡的教學。