用纖細框架印出 Hello World

本教學示範使用纖細框架撰寫應用程式的標準流程。纖細框架會利用前端控制器模式,將所有 HTTP 要求透過一個單一檔案傳送,通常是 index.php。預設情況下,纖細框架會附帶一個 .htaccess 檔案供 Apache 網頁伺服器使用。您通常會在 ``index.php` 中初始化應用程式,定義路由,並執行應用程式。

步驟 1:初始化應用程式

首先,實例化您的纖細框架應用程式。提供一個設定陣列(可選),以設定應用程式。

//With default settings
$app = new Slim();

//With custom settings
$app = new Slim(array(
    'log.enable' => true,
    'log.path' => './logs',
    'log.level' => 4,
    'view' => 'MyCustomViewClassName'
));

步驟 2:定義路由

第三步,使用以下範例中所示的方法定義應用程式的路由。

建議您使用 PHP >= 5.3 來享受纖細框架對匿名函式的支援。如果使用較低版本的 PHP 版本,最後一個引數可以是任何對 is_callable() 回傳 true 的值。

//GET route
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});

//POST route
$app->post('/person', function () {
    //Create new Person
});

//PUT route
$app->put('/person/:id', function ($id) {
    //Update Person identified by $id
});

//DELETE route
$app->delete('/person/:id', function ($id) {
    //Delete Person identified by $id
});

步驟 3:執行應用程式

最後,執行您的纖細框架應用程式。這通常會是 index.php 檔案中執行的最後一個陳述式。

$app->run();