cakephpでsmartyを使う
1. smartyとは
PHP のためのテンプレートエンジン。
PHPのプレゼンテーションからアプリケーションのロジックとコンテンツを分離して管理する事を容易にする。
2. 特徴
- 非常に高速
- 下仕事は PHP パーサが行うので能率的
- コンパイルは一度だけ行われるので、テンプレートのパースによるオーバーヘッドが無い
- 再コンパイル は変更があったテンプレートファイルのみで行うのでスマート
- 組み込みで キャッシュ機能 をサポート
などなど
3. 記法
HTML中に埋め込む変数やループ、条件分岐などの制御構造などを記述するのに{}を用いる。
コメント { ... }
4. 導入の仕方
A 公式ページからsmartyをインストール
この、libsディレクトリをsmartyにrename、そしてapp/Vendorの中に置く!
B ViewフォルダにSmartyViewを設置
app/Viewの下にSmartyView.phpを作る。
<?php class SmartyView extends View { function __construct (&$controller) { parent::__construct($controller); if (is_object($controller)) { $count = count($this->_passedVars); for ($j = 0; $j < $count; $j++) { $var = $this->_passedVars[$j]; $this->{$var} = $controller->{$var}; } } if(!App::import('Vendor', 'Smarty', array('file' => 'smarty'.DS.'Smarty.class.php'))) die('error Loading Smarty Class'); $this->Smarty = new Smarty(); //$this->subDir = 'smarty'.DS; $this->ext= '.tpl'; //$this->Smarty->plugins_dir[] = VENDORS.DS.'smarty'.DS.'plugins'; $this->Smarty->compile_dir = TMP.'smarty'.DS.'compile'.DS; $this->Smarty->cache_dir = TMP.'smarty'.DS.'cache'.DS; $this->Smarty->error_reporting = 'E_ALL & ~E_NOTICE'; $this->Smarty->debugging = true; $this->Smarty->compile_check = true; $this->viewVars['params'] = $this->params; $this->Helpers = new HelperCollection($this); } protected function _render($___viewFn, $___dataForView = array()) { $trace = debug_backtrace(); $caller = array_shift($trace); if ($caller === "element") parent::_render($___viewFn, $___dataForView); if (empty($___dataForView)) { $___dataForView = $this->viewVars; } extract($___dataForView, EXTR_SKIP); foreach($___dataForView as $data => $value) { if(!is_object($data)) { $this->Smarty->assign($data, $value); } } $this->Smarty->assign('View', new View(null)); ob_start(); $this->Smarty->display($___viewFn); return ob_get_clean(); } public function loadHelpers() { $helpers = HelperCollection::normalizeObjectArray($this->helpers); foreach ($helpers as $name => $properties) { list($plugin, $class) = pluginSplit($properties['class']); $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']); $this->Smarty->assign($name, $this->{$class}); } $this->_helpersLoaded = true; } } ?>
- レイアウトファイルを置く所を、app/View/Layoutsの中にしたい→ // $this->subDir = 'smarty'.DS;
C AppControllerにsmartyを指定
app/Controller/AppController.php
class AppController extends Controller { public $viewClass = 'Smarty'; }
完了だが、、、、、サンプルを作成してみよう!
D app/Controller/SamplesController.phpを作成。そしてapp/View/samples/index.tplを作成。
<?php class SamplesController extends AppController { public $viewClass = 'Smarty'; public function index() { $this->set('sampleValue', 'サンプルテキスト'); } } index.tpl <h1>{$sampleValue}</h1> {$this->Html->link('Yahoo', 'http://www.yahoo.co.jp/')}
http://localhost/cakephp/samples/にアクセスしてみよう!!