facebook twitter hatena line email

Php/zend framework/smarty3用

提供: 初心者エンジニアの簡易メモ
2026年4月23日 (木) 11:59時点におけるAdmin (トーク | 投稿記録)による版

移動: 案内検索

Smarty3のCustom_View_Smartyサンプル

<?php
//require_once APPLICATION_PATH . '/../library/Smarty-2.6.18/libs/Smarty.class.php';
require_once APPLICATION_PATH . '/../library/Smarty-3.1.11/libs/Smarty.class.php';
require_once 'Zend/View/Interface.php';
/**
 * @url http://framework.zend.com/manual/ja/zend.view.scripts.html#zend.view.scripts.templates.interface
 */
class Custom_View_Smarty implements Zend_View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    protected $_smarty;

    /**
     * コンストラクタ
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
   public function __construct($tmplPath = null, $extraParams = array(), $smartyObject = null)
   {
       $this->_smarty = new Smarty;

       if ($smartyObject) {
           $this->_smarty = $smartyObject;
       }
       if (null !== $tmplPath) {
           $this->setScriptPath($tmplPath);
       }

       if ($extraParams) {
           foreach ($extraParams as $key => $value) {
               if ($key == 'template_dir') {
                   $this->_smarty->setTemplateDir($value);
               } elseif ($key == 'compile_dir') {
                   $this->_smarty->setCompileDir($value);
               } elseif ($key == 'cache_dir') {
                   $this->_smarty->setCacheDir($value);
               } elseif ($key == 'right_delimiter') {
                   $this->_smarty->setRightDelimiter($value);
               } elseif ($key == 'left_delimiter') {
                   $this->_smarty->setLeftDelimiter($value);
               } else {
                   // その他、存在するsetterがあれば使う
                   $setter = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
                   if (method_exists($this->_smarty, $setter)) {
                       $this->_smarty->$setter($value);
                   } else {
                       // 最終手段: 直接アクセスできるプロパティのみ
                       if (property_exists($this->_smarty, $key)) {
                           $this->_smarty->$key = $value;
                       }
                   }
               }
           }
       }
   }

   /**
    * テンプレートエンジンオブジェクトを返します
    *
    * @return Smarty
    */
   public function getEngine()
   {
       return $this->_smarty;
   }

   /**
    * テンプレートへのパスを設定します
    *
    * @param string $path パスとして設定するディレクトリ
    * @return void
    */
   public function setScriptPath($path)
   {
       if (is_readable($path)) {
           $this->_smarty->setTemplateDir($path);
           return;
       }

       throw new Exception('無効なパスが指定されました');
   }
   
   /**
    * 現在のテンプレートディレクトリを取得します
    *
    * @return string
    */
   public function getScriptPaths()
   {
       return $this->_smarty->getTemplateDir();
   }

   /**
    * setScriptPath へのエイリアス
    *
    * @param string $path
    * @param string $prefix Unused
    * @return void
    */
   public function setBasePath($path, $prefix = 'Zend_View')
   {
       return $this->setScriptPath($path);
   }

   /**
    * setScriptPath へのエイリアス
    *
    * @param string $path
    * @param string $prefix Unused
    * @return void
    */
   public function addBasePath($path, $prefix = 'Zend_View')
   {
       return $this->setScriptPath($path);
   }

   /**
    * 変数をテンプレートに代入します
    *
    * @param string $key 変数名
    * @param mixed $val 変数の値
    * @return void
    */
   public function __set($key, $val)
   {
       $this->_smarty->assign($key, $val);
   }

  /**
   * empty() や isset() のテストが動作するようにします
   *
   * @param string $key
   * @return boolean
   */
  public function __isset($key)
  {
      return (null !== $this->_smarty->get_template_vars($key));
  }

  /**
   * オブジェクトのプロパティに対して unset() が動作するようにします
   *
   * @param string $key
   * @return void
   */
  public function __unset($key)
  {
      $this->_smarty->clear_assign($key);
  }

  /**
   * 変数をテンプレートに代入します
   *
   * 指定したキーを指定した値に設定します。あるいは、
   * キー => 値 形式の配列で一括設定します
   *
   * @see __set()
   * @param string|array $spec 使用する代入方式 (キー、あるいは キー => 値 の配列)
   * @param mixed $value (オプション) 名前を指定して代入する場合は、ここで値を指定します
   * @return void
   */
  public function assign($spec, $value = null)
  {
      if (is_array($spec)) {
          $this->_smarty->assign($spec);
          return;
      }

      $this->_smarty->assign($spec, $value);
  }

  /**
   * 代入済みのすべての変数を削除します
   *
   * Zend_View に {@link assign()} やプロパティ
   * ({@link __get()}/{@link __set()}) で代入された変数をすべて削除します
   *
   * @return void
   */
  public function clearVars()
  {
      $this->_smarty->clear_all_assign();
  }

  /**
   * テンプレートを処理し、結果を出力します
   *
    * @param string $name 処理するテンプレート
    * @return string 出力結果
    */
   public function render($name)
   {
       return $this->_smarty->fetch($name);
   }
}

==キャッシュ対応追加==
上のCustom_View_Smartyクラスに拡張を追加
<pre>
  // 以下拡張
  /**
   * テンプレートを処理し、結果を出力します
   *
   * @param string $name 処理するテンプレート
   * @return string 出力結果
   */
  public function render($name, $cache_id = null, $compile_id = null, $display = false)
  {
      return $this->_smarty->fetch($name, $cache_id, $compile_id, $display);
  }
  /**
   * キャッシュが判定
   *
   * @param string $name
   * @param string $cache_id
   */
  public function isCached($name, $cache_id = null, $compile_id = null)
  {
          return $this->_smarty->is_cached($name, $cache_id, $compile_id);
  }

smarty2から3に変えた際にsetEngine()が無いエラーが出るとき

エラー詳細

Fatal error: Call to undefined method Custom_View_Smarty::setEngine() in

修正前

$view = new Custom_View_Smarty();
$smarty = new SmartyModel();
$view->setEngine($smarty);

修正後

$smarty = new SmartyModel();
$extraParams = [
    'compile_dir' => $smarty->getCompileDir(),
    'cache_dir' => $smarty->getCacheDir(),
    'template_dir' => $smarty->getTemplateDir(),
    'right_delimiter' => $smarty->getRightDelimiter(),
    'left_delimiter' => $smarty->getLeftDelimiter(),
];
$view = new Custom_View_Smarty(null, $extraParams, $smarty);

setViewBasePathSpecは、配列無理なので修正

$templates = $smarty->template_dir[0]; // setViewBasePathSpecは配列無理なので、template_dir[0]から文字列取得。
$view->setEngine($smarty);
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setView($view)
->setViewBasePathSpec($templates)

escape関数などが使えないエラーが出る場合

公式のpluginsが読み込めてないので、以下のような感じで、公式のpluginsを追加する。

修正前

$this->plugins_dir[] = __DIR__ . '/smartyPlugins';

修正後

$this->setPluginsDir([
   APPLICATION_PATH . '/../library/smarty-3.1.39/libs/plugins',
    __DIR__ . '/smartyPlugins',
]);

テンプレの相対パスエラー

エラー詳細

Fatal error: Uncaught exception 'SmartyException' with message 'Unable to load template 'file:../../../../views/templates/parts/smartphone/ad/main_320x50.tpl 

エラーテンプレコード

{{include file="../../../../views/templates/parts/smartphone/ad/main_320x50.tpl"}}

複数templateを設定するように。

修正前

$this->template_dir = __DIR__ . "/../views/templates";

修正後

$this->setTemplateDir([
    __DIR__ . '/../views/templates',
    APPLICATION_PATH . '/views/templates', // 追加テンプレ
]);

テンプレを以下のように直す。

{{include file="parts/smartphone/ad/main_320x50.tpl"}}

=={{php}}タグを使う==
Smarty.class.phpをSmartyBC.class.phpへ。
クラスも、Smartyじゃなく、SmartyBCを使う。