ComposerでSmartyを入れて遊ぶだけ
Composer
最近のPHPerには必須のツール。PHP系ライブラリをインストールする際、依存関係を標準的に管理してくれる。(ある ライブラリをインストールした際、あのライブラリも要るのかあ、という状況を解決してくれる)
Smarty
PHPのテンプレートエンジン。nodeでいうEJSなどである。
ComposerをMacにインストール
環境はMac OS Sierraでやっていきます。
まず、Composerのインストーラをcurl
で取得、その後インストーラをPHPで実行します。
curl -sS https://getcomposer.org/installer | php
次にcomposer.phar
を移動します。
mv composer.phar /usr/local/bin/composer
入れたComposerのバージョンを確認するにはcomposer -V
で調べます。
Smartyを入れる
なんか適当にディレクトリをつくって、その中に潜りましょう。
mkdir smarty_app cd smarty_app
先にcomposer.json
を書いてインストールしても良いですが、面倒なのでcomposer requrie
というコマンドを
使います。このコマンドを使った場合、composer.json
は勝手に作成されます。
composer require smarty/smarty
現時点でのsmarty_app
の中の構成はこのような感じになっているはずです。
composer.json composer.lock vendor
vendor
の中を見ると、ちゃんとsmartyが入っています。
必要最小限の構築
次にtemplates
というディレクトリと、templates_c
というディレクトリを作成します。
そして、このtemplates_c
の権限を変えます。
mkdir templates mkdir templates_c chmod 777 templates_c
このtemplates_c
というディレクトリは必須です。ここではあんまり良くないですが、777で許可しています。
イメージとしては、templates
というディレクトリに入っているテンプレートが、自動的にコンパイルされて
templates_c
に入ります。(cはコンパイルのcみたいですね)
使ってみる
index.php
をsmarty_app
直下につくります。
<?php require_once 'vendor/autoload.php'; ini_set('date.timezone', 'Asia/Tokyo'); define('MY_TITLE', 'TEST'); $smarty = new Smarty(); // 使うテンプレートが入っているディレクトリを指定 $smarty->setTemplateDir('./templates/'); $smarty->assign('hello', 'Hello, Smarty!!'); $smarty->assign('today', new DateTime()); $smarty->assign('animal', array('rabbit','cat','dog')); $smarty->display('index.tpl');
つづいて、templates
内にhader.tpl
、index.tpl
を作成。
header.tpl
<!DOCTYPE html> <meta charset="utf-8"> <title> {$page_title} </title>
index.tpl
{* コメントアウト *} {include file='header.tpl' page_title={$smarty.const.MY_TITLE}} {* 普通の変数 *} <p>{$hello} {* メソッド *} <p>{$today->format('Y/m/d (D)')} {* 予約変数 *} <dl> <dt>現在のタイムスタンプ <dd>{$smarty.now} <dt>現在処理中のテンプレートファイル名 <dd>{$smarty.template} <dt>Smarty version <dd>{$smarty.version} <dl> {* 配列を逆順でループ(step=-1だから) *} <ul> {section name=i loop=$animal step=-1} <li>{$animal[i]} {/section} </ul>
一応smarty_app
内の構造を記しておきます。
|--composer.json |--composer.lock |--index.php |--templates | |--header.tpl | |--index.tpl |--templates_c |--vendor
つくったら、PHPのビルトインサーバを立てるなりして、http://localhost/~
なんかでアクセスします。
成功していればブラウザ上に、Smartyのバージョンや現在の日付なんかが表示されるはずです。
templates_c
内を見ると、コンパイルされたファイルがあるのもわかるはずです。