-
Notifications
You must be signed in to change notification settings - Fork 0
Routing
tsubo edited this page Oct 12, 2014
·
9 revisions
Slim FrameworkのRouting機能を使用すると、URLとPHPの処理を関連付け、PHPで処理した結果をTwigテンプレートで表示することが出来ます。
ここでは簡単な「おみくじ」ページを作成して Slim Frameworkの使い方をご紹介します。
Chocoでは controller/routing.phpに ユーザが定義する URLとPHPの処理を記述します。
contoller/routing.php
/*
* GETメソッドで /omikuji がリスエストされたら
* ランダムにおみくじの結果を決めて
* omikuji.html.twigを表示する
*/
$app->get('/omikuji', function () use ($app){
// おみくじの結果
$omikuji = array('大吉', '中吉', '小吉', '吉', '末吉', '凶', '大凶');
// おみくじ結果に対応する色
$colors = array('success', 'success', 'info', 'info', 'info', 'warning', 'danger');
// ランダムにおみくじの結果を決める
$index = array_rand($omikuji);
// babymetalの画像を取得
$babymetal = get_image('babymetal');
// テンプレートに渡すパラメータ配列をセット
$data = array(
'result' => $omikuji[$index],
'color' => $colors[$index],
'image' => $babymetal
);
// テンプレートを表示
$app->render('page/omikuji.html.twig', $data);
});
function get_image($key) {
$url = "http://ajax.googleapis.com/ajax/services/search/images?q=${key}&v=1.0";
$json = json_decode(file_get_contents($url), true);
$results = $json['responseData']['results'];
$index = array_rand($results);
return $results[$index]['url'];
}
page/omikuji.html.twig
{% extends "layout/base.html.twig" %}
{% block page_title %}おみくじ{% endblock %}
{% block body_id %}omikuji{% endblock %}
{% block doc_header %}
{% embed 'partial/doc_header.html.twig' %}
{% block content %}
<h1>おみくじ</h1>
<p class="lead">あなたの今日の運勢をBABYMETALが占います。</p>
{% endblock %}
{% endembed %}
{% endblock %}
{% block layout %}
{% embed 'layout/12.html.twig' %}
{% block content %}
<div class="alert alert-{{ color }}"> <-- 'color'パラメータを展開(BootstrapのCSSで色を指定)
<h2>{{ result }} Death!!</h2> <-- 'result'パラメータを展開(おみくじの結果を表示)
</div>
<img class="img-responsive" src="{{ image }}"> <-- 'image'パラメータを展開(画像URL)
{% endblock %}
{% endembed %}
{% endblock %}
http://localhost:8000/omikuji を表示して動作確認。
リロードする度におみくじの結果が変るはずです。
Slim Frameworkには上記以外にも様々な便利な機能があります。
詳細は Slim Frameworkのドキュメントをご参照ください。
- Home
- Getting Started
- Deployment
- Environment
- Component
- Directory Structure
- Configration
- Your Contents
- Default Pages
- Admin
- Blog
- Template
- Design
- Theme
- Customization
- Routing
- Json Schema
- Custom Field
- Custom Post
- Debug