Slim Step1
ファイル構成
project/
|- htdocs/
| index.php # Step1-3
|- templates/
| index.php # Step1-4
| test.php # Step1-5
|- vendor/ ★Vendorディレクトリ以下は、Step1-1で自動生成される
|+ composer/
|+ slim/
| autoload.php
| composer.json # Step1-1
| config.php # Step1-2
Step1の手順
- composer.json: Composerでライブラリをインストール
- config.php
- htdocs/index.php
- templates/index.php
- templates/test.php
1-1. composer.json
TODO: Composerでのセットアップ、composer.jsonについて書くこと!
{
"require": {
"slim/slim": "2.*"
},
"autoload": {
"psr-0": {"": "lib/"}
}
}
1-2. config.php
テンプレートパスの定義をする
<?php
define('TEMPLATES_DIR_PATH', __DIR__.'/templates');
__DIR__はカレントディレクトリパスなので、この場合は「project/templates」がテンプレート用のパスとなる
1-3. htdocs/index.php
ここではslimのインスタンスを作成、ルートの設定などしてイニシャルが終わったら$app->run()する
- autoload.phpとテンプレートパスの定義をしたプロジェクトディレクトリにあるconfig.phpをrequireする
- index.phpにテンプレートディレクトリのパスを通す
- テンプレートの呼び出し
<?php
require "../vendor/autoload.php";
// TEMPLATES_DIR_PATHの定義
require "../config.php";
$app = new \Slim\Slim([
"templates.path" => TEMPLATES_DIR_PATH
]);
$app->get('/', function () use ($app) {
$app->render("index.php");
});
// GET
$app->get("/test/", function () use ($app) {
$message= $app->request->get("message");
$app->render("test.php", ["message" => $message]);
});
$app->run();
1-4. templates/index.php
このtextarea nameの「message」がhtdocs/index.phpの
$app->get("/test/", function() use ($app){
$message=$app->request->get("message");
で$messageに取り込まれ、
$app->render("test.php", ["message" => $message]);});
で$messageがtest.phpに渡されます。
このactionの"/test/"とhtdocs/index.phpでgetに登録する'/test/'を合わすこと!
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Slim Study</title>
</head>
<body>
<h1>Slim Study</h1>
<h2>templates/index.php</h2>
<form method="GET" action="/test/">
<p>メッセージ:<br>
<textarea name="message"></textarea></p>
<p><input type="submit" value="送信する"></p>
</form>
<footer>
<a href="/">return to HOME</a>
</footer>
</body>
</html>
1-5. templates/test.php
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>テストのページ</title>
</head>
<body>
<h1>呼ばれたテストのページ</h1>
<p>
<?php echo "$message さんです"; ?>
</p>
<footer>
<a href="/">return to HOME</a>
</footer>
</body>
</html>
最終更新:2014年04月09日 00:04