IThaiのブログ

IT関連の話題やタイに関する様々なことを書いていきます。

PHPでSmartyを使う

普段、Javaを使って開発しているが、急にPHPを触りたくなった。 3年前にPHPを学んだが、そのときは素のPHPしか利用してなかったし、オブジェクト指向的なPHPも知らなかったので、これから改めて勉強してこうと思います。

今回はテンプレートエンジンである、Smartyを使ってみました。

PHP Template Engine | Smarty

git clone https://github.com/smarty-php/smarty.git

gitでインストールしたsmartyフォルダと同じディレクトリに、ControllerとViewを置いて試します。

フォルダ構成はこんな感じです。

app2/
├── index.php
├── smarty
│   ├── COMPOSER_RELEASE_NOTES.txt
│   ├── COPYING.lib
・
・
・
├── templates
│   └── index.html
└── templates_c
    └── <コンパイルされたテンプレートが置かれる>

templatesとtemplates_cを作成する必要があって、templatesにはあらかじめViewを作成します。templates_cにはPHPにコンパイルされたテンプレートが置かれます。

index.php (Controller)

<?php

require_once 'smarty/libs/Smarty.class.php';

$smarty = new Smarty();
$smarty->template_dir = 'templates/';
$smarty->compile_dir  = 'templates_c/';
$smarty->assign('sample1', 'hello');
$smarty->display('index.html');
?>

index.html (View)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
</head>
<body>
<div>{$sample1}</div>
</body>
</html>

今回はPHPのテンプレートエンジンを少し触ってみたけど、PHPはJavaと違ってアプリケーションサーバとか使わずに、気軽にWebアプリが作れるのが楽しい。これからもPHPを色々触ってみて、Javaとの違いみたいなものを感じていきたいです。

Smarty 3を覚える本

Smarty 3を覚える本