WebEngine

だらだらと綴る技術系メモ

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.phpsmarty_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.tplindex.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内を見ると、コンパイルされたファイルがあるのもわかるはずです。

参考