facebook twitter hatena line email

「Php/zend framework/smarty3用」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(smarty2から3に変えた際にsetEngine()が無いエラーが出るとき)
(Smarty3のCustom_View_Smartyサンプル)
 
(同じ利用者による、間の17版が非表示)
行1: 行1:
<?php
+
==Smarty3のCustom_View_Smartyサンプル==
//require_once APPLICATION_PATH . '/../library/Smarty-2.6.18/libs/Smarty.class.php';
+
<pre>
require_once APPLICATION_PATH . '/../library/Smarty-3.1.11/libs/Smarty.class.php';
+
<?php
require_once 'Zend/View/Interface.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';
  * @url http://framework.zend.com/manual/ja/zend.view.scripts.html#zend.view.scripts.templates.interface
+
require_once 'Zend/View/Interface.php';
  */
+
/**
class Custom_View_Smarty implements Zend_View_Interface
+
* @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);
+
                } else {
+
                    $this->_smarty->$key = $value;
+
                }
+
            }
+
        }
+
    }
+
+
 
     /**
 
     /**
     * テンプレートエンジンオブジェクトを返します
+
     * Smarty object
    *
+
     * @var Smarty
     * @return Smarty
+
 
     */
 
     */
     public function getEngine()
+
     protected $_smarty;
    {
+
 
        return $this->_smarty;
+
    }
+
+
 
     /**
 
     /**
     * テンプレートへのパスを設定します
+
     * コンストラクタ
 
     *
 
     *
     * @param string $path パスとして設定するディレクトリ
+
     * @param string $tmplPath
 +
    * @param array $extraParams
 
     * @return void
 
     * @return void
 
     */
 
     */
    public function setScriptPath($path)
+
  public function __construct($tmplPath = null, $extraParams = array(), $smartyObject = null)
    {
+
  {
        if (is_readable($path)) {
+
      $this->_smarty = new Smarty;
            $this->_smarty->setTemplateDir($path);
+
 
            return;
+
      if ($smartyObject) {
        }
+
          $this->_smarty = $smartyObject;
+
      }
        throw new Exception('無効なパスが指定されました');
+
      if (null !== $tmplPath) {
    }
+
          $this->setScriptPath($tmplPath);
   
+
      }
    /**
+
 
    * 現在のテンプレートディレクトリを取得します
+
      if ($extraParams) {
    *
+
          foreach ($extraParams as $key => $value) {
    * @return string
+
              if ($key == 'template_dir') {
    */
+
                  $this->_smarty->setTemplateDir($value);
    public function getScriptPaths()
+
              } elseif ($key == 'compile_dir') {
    {
+
                  $this->_smarty->setCompileDir($value);
        return $this->_smarty->getTemplateDir();
+
              } elseif ($key == 'cache_dir') {
    }
+
                  $this->_smarty->setCacheDir($value);
+
              } elseif ($key == 'right_delimiter') {
    /**
+
                  $this->_smarty->setRightDelimiter($value);
    * setScriptPath へのエイリアス
+
              } elseif ($key == 'left_delimiter') {
    *
+
                  $this->_smarty->setLeftDelimiter($value);
    * @param string $path
+
              } else {
    * @param string $prefix Unused
+
                  // その他、存在するsetterがあれば使う
    * @return void
+
                  $setter = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
    */
+
                  if (method_exists($this->_smarty, $setter)) {
    public function setBasePath($path, $prefix = 'Zend_View')
+
                      $this->_smarty->$setter($value);
    {
+
                  } else {
        return $this->setScriptPath($path);
+
                      // 最終手段: 直接アクセスできるプロパティのみ
    }
+
                      if (property_exists($this->_smarty, $key)) {
+
                          $this->_smarty->$key = $value;
    /**
+
                      }
    * 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 Smarty
     * @return boolean
+
 
     */
 
     */
   public function __isset($key)
+
   public function getEngine()
 
   {
 
   {
       return (null !== $this->_smarty->get_template_vars($key));
+
       return $this->_smarty;
 
   }
 
   }
+
 
 
   /**
 
   /**
     * オブジェクトのプロパティに対して unset() が動作するようにします
+
     * テンプレートへのパスを設定します
 
     *
 
     *
     * @param string $key
+
     * @param string $path パスとして設定するディレクトリ
 
     * @return void
 
     * @return void
 
     */
 
     */
   public function __unset($key)
+
   public function setScriptPath($path)
 
   {
 
   {
       $this->_smarty->clear_assign($key);
+
       if (is_readable($path)) {
 +
          $this->_smarty->setTemplateDir($path);
 +
          return;
 +
      }
 +
 
 +
      throw new Exception('無効なパスが指定されました');
 
   }
 
   }
+
 
 
   /**
 
   /**
     * 変数をテンプレートに代入します
+
     * 現在のテンプレートディレクトリを取得します
 
     *
 
     *
     * 指定したキーを指定した値に設定します。あるいは、
+
     * @return string
     * キー => 値 形式の配列で一括設定します
+
     */
 +
  public function getScriptPaths()
 +
  {
 +
      return $this->_smarty->getTemplateDir();
 +
  }
 +
 
 +
  /**
 +
    * setScriptPath へのエイリアス
 
     *
 
     *
    * @see __set()
+
     * @param string $path
     * @param string|array $spec 使用する代入方式 (キー、あるいは キー => 値 の配列)
+
     * @param string $prefix Unused
     * @param mixed $value (オプション) 名前を指定して代入する場合は、ここで値を指定します
+
 
     * @return void
 
     * @return void
 
     */
 
     */
   public function assign($spec, $value = null)
+
   public function setBasePath($path, $prefix = 'Zend_View')
 
   {
 
   {
       if (is_array($spec)) {
+
       return $this->setScriptPath($path);
          $this->_smarty->assign($spec);
+
          return;
+
      }
+
+
      $this->_smarty->assign($spec, $value);
+
 
   }
 
   }
+
 
 
   /**
 
   /**
     * 代入済みのすべての変数を削除します
+
     * setScriptPath へのエイリアス
    *
+
    * Zend_View に {@link assign()} やプロパティ
+
    * ({@link __get()}/{@link __set()}) で代入された変数をすべて削除します
+
 
     *
 
     *
 +
    * @param string $path
 +
    * @param string $prefix Unused
 
     * @return void
 
     * @return void
 
     */
 
     */
   public function clearVars()
+
   public function addBasePath($path, $prefix = 'Zend_View')
 
   {
 
   {
       $this->_smarty->clear_all_assign();
+
       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 処理するテンプレート
 
     * @param string $name 処理するテンプレート
 
     * @return string 出力結果
 
     * @return string 出力結果
行183: 行200:
 
       return $this->_smarty->fetch($name);
 
       return $this->_smarty->fetch($name);
 
   }
 
   }
}
+
}
 
+
</pre>
==smarty2から3に変えた際にsetEngine()が無いエラーが出るとき==
+
エラー詳細
+
Fatal error: Call to undefined method Custom_View_Smarty::setEngine() in
+
  
 +
==キャッシュ対応追加==
 
上のCustom_View_Smartyクラスに拡張を追加
 
上のCustom_View_Smartyクラスに拡張を追加
 
<pre>
 
<pre>
 
   // 以下拡張
 
   // 以下拡張
 
 
   /**
 
   /**
   * テンプレートエンジンオブジェクトを設定します
+
   * テンプレートを処理し、結果を出力します
 
   *
 
   *
   * @param Smarty
+
   * @param string $name 処理するテンプレート
   * @return void
+
   * @return string 出力結果
 
   */
 
   */
   public function setEngine($smarty)
+
   public function render($name, $cache_id = null, $compile_id = null, $display = false)
 
   {
 
   {
       $this->_smarty = $smarty;
+
       return $this->_smarty->fetch($name, $cache_id, $compile_id, $display);
 
   }
 
   }
 
   /**
 
   /**
行214: 行228:
 
   }
 
   }
 
</pre>
 
</pre>
 +
 +
==smarty2から3に変えた際にsetEngine()が無いエラーが出るとき==
 +
エラー詳細
 +
Fatal error: Call to undefined method Custom_View_Smarty::setEngine() in
 +
 +
修正前
 +
<pre>
 +
$view = new Custom_View_Smarty();
 +
$smarty = new SmartyModel();
 +
$view->setEngine($smarty);
 +
</pre>
 +
修正後
 +
<pre>
 +
$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);
 +
</pre>
 +
 +
==setViewBasePathSpecは、配列無理なので修正==
 +
<pre>
 +
$templates = $smarty->template_dir[0]; // setViewBasePathSpecは配列無理なので、template_dir[0]から文字列取得。
 +
$view->setEngine($smarty);
 +
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
 +
$viewRenderer->setView($view)
 +
->setViewBasePathSpec($templates)
 +
</pre>
 +
 +
==escape関数などが使えないエラーが出る場合==
 +
公式のpluginsが読み込めてないので、以下のような感じで、公式のpluginsを追加する。
 +
 +
修正前
 +
<pre>
 +
$this->plugins_dir[] = __DIR__ . '/smartyPlugins';
 +
</pre>
 +
 +
修正後
 +
<pre>
 +
$this->setPluginsDir([
 +
  APPLICATION_PATH . '/../library/smarty-3.1.39/libs/plugins',
 +
    __DIR__ . '/smartyPlugins',
 +
]);
 +
</pre>
 +
 +
==テンプレの相対パスエラー==
 +
エラー詳細
 +
Fatal error: Uncaught exception 'SmartyException' with message 'Unable to load template 'file:../../../../views/templates/parts/smartphone/ad/main_320x50.tpl''
 +
 +
エラーテンプレコード
 +
<pre>
 +
{{include file="../../../../views/templates/parts/smartphone/ad/main_320x50.tpl"}}
 +
</pre>
 +
 +
複数templateを設定するように。
 +
 +
修正前
 +
$this->template_dir = __DIR__ . "/../views/templates";
 +
 +
修正後
 +
<pre>
 +
$this->setTemplateDir([
 +
    __DIR__ . '/../views/templates',
 +
    APPLICATION_PATH . '/views/templates', // 追加テンプレ
 +
]);
 +
</pre>
 +
 +
テンプレを以下のように直す。
 +
<pre>
 +
{{include file="parts/smartphone/ad/main_320x50.tpl"}}
 +
 +
=={{php}}タグを使う==
 +
Smarty.class.phpをSmartyBC.class.phpへ。
 +
クラスも、Smartyじゃなく、SmartyBCを使う。

2026年4月23日 (木) 12:00時点における最新版

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クラスに拡張を追加

  // 以下拡張
  /**
   * テンプレートを処理し、結果を出力します
   *
   * @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を使う。