教學 - kouji6309/SingleMVC GitHub Wiki
從最簡單的 Hello World 開始吧。這裡選用單一檔案的目錄結構,假設網址為 http://localhost/welcome/ ,因此可以建立 index.php
:
<?php
require 'SingleMVC.php';
// 定義控制器
class welcome extends Controller {
public function index() {
output('text', 'Hello World');
}
}
開啟網頁後,就可以看到輸出文字
Hello World
範例中會把一些資料傳遞到 View,並顯示到畫面中。
這次選用分離檔案的結構,目錄與檔案長這樣:
網站根目錄
├ source
│ ├ controllers
│ │ └ welcome.php
│ └ views
│ └ home.php
├ .htaccess (或 web.config)
└ index.php
然後在 welcome.php
中寫下:
<?php defined('ROOT') or die('Access denied');
class welcome extends Controller {
public function index() {
$data = [
'title' => '歡迎使用 SingleMVC',
'href' => 'https://github.com/kouji6309/SingleMVC',
];
output('home', $data);
}
}
接著在 home.php
中寫下:
<?php defined('ROOT') or die('Access denied'); ?>
<!DOCTYPE html>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<a target="_blank" href="<?=$href?>">
<?=$title?>
</a>
</body>
</html>
最後開啟 http://localhost/welcome/ ,即可看到畫面中一個超連結:
最後,我們使用以下結構 (你可以從上一個範例修改):
網站根目錄
├ source
│ ├ controllers
│ │ └ welcome.php
│ ├ models
│ │ └ main.php
│ └ views
│ └ home.php
├ .htaccess (或 web.config)
└ index.php
在 welcome.php
中寫下:
<?php defined('ROOT') or die('Access denied');
class welcome extends Controller {
public function index() {
$m = new main();
$data = [
'title' => '歡迎使用 SingleMVC',
'token' => $m->getToken(),
];
output('home', $data);
}
}
在 main.php
中寫下:
<?php defined('ROOT') or die('Access denied');
class main extends Model {
public function getToken() {
return jwt_encode([
'usernmae' => 'kouji6309',
'name' => 'Kouji',
], 'my password');
}
}
最後在 home.php
中寫下:
<!DOCTYPE html>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
產生的 TOKEN 為 <code><?=$token?></code>
</body>
</html>
執行!可以看到顯示:
產生的 TOKEN 為 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm1hZSI6ImtvdWppNjMwOSIsIm5hbWUiOiJLb3VqaSJ9.9Bj0bbY2LtIWZyLykOGATpWt5ek3UwZ4EfXKEHAR8Uc
基礎教學就到這邊結束囉,接著可以看控制器與路由。