目次
{#$title#}
ホームページ バックエンド開発 PHPチュートリアル yii,CI,yaf框架+smarty模板使用方法_PHP

yii,CI,yaf框架+smarty模板使用方法_PHP

May 28, 2016 am 11:49 AM
ci smarty yaf yii フレーム テンプレート

本文实例讲述了yii,CI,yaf框架+smarty模板使用方法。分享给大家供大家参考,具体如下:

最近折腾了框架的性能测试,其中需要测试各个模板跟smarty配合的性能,所以折腾了一桶,现总结一下。之前已经写过kohana框架+smarty模板,这里不再重复了。

一、yii框架+smarty模板

yii是覆盖了viewRenderer组件。

1.1,下载yii框架并解压,下载smarty框架并解压,将smarty/libs文件夹拷到yii框架application/protected/vendors下面,并重命名smarty。

1.2,yii配置文件main.php

'components'=>array(
 'viewRenderer' => array(
  'class'=>'batman.protected.extensions.SmartyViewRender',
  // 这里为Smarty支持的属性
  'config' => array (
    'left_delimiter' => "{#",
    'right_delimiter' => "#}",
    'template_dir' => APP_DIR . "/views/",
    'config_dir' => APP_DIR . "/views/conf/",
    'debugging' => false,
    'compile_dir' => 'D:/temp/runtime',
  )
)

ログイン後にコピー

其中batman是我已经在index.php定义好的别名。

Yii::setPathOfAlias('batman', dirname(__FILE__));
Yii::import("batman.protected.vendors.*");
define('APP_DIR', dirname(__FILE__).'/protected/');

ログイン後にコピー

1.3,在protected/extensions/下面新建SmartyViewRender.php

<&#63;php
class SmartyViewRender extends CApplicationComponent implements IViewRenderer {
 public $fileExtension = '.html';
 private $_smarty = null;
 public $config = array();
 public function init() {
  $smartyPath = Yii::getPathOfAlias('batman.protected.vendors.smarty');
  Yii::$classMap['Smarty'] = $smartyPath . '/Smarty.class.php';
  Yii::$classMap['Smarty_Internal_Data'] = $smartyPath . '/sysplugins/smarty_internal_data.php';
  $this->_smarty = new Smarty();
  // configure smarty
  if (is_array ( $this->config )) {
   foreach ( $this->config as $key => $value ) {
    if ($key {0} != '_') { // not setting semi-private properties
     $this->_smarty->$key = $value;
    }
   }
  }
  Yii::registerAutoloader('smartyAutoload');
 }
 public function renderFile($context, $file, $data, $return) {
   foreach ($data as $key => $value)
    $this->_smarty->assign($key, $value);
  $return = $this->_smarty->fetch($file);
  if ($return)
    return $return;
  else
    echo $return;
 }
}

ログイン後にコピー

1.4,验证

新建一个HelloController.php

<&#63;php
class HelloController extends Controller {
 public function actionWorld() {
  $this->render('world', array('content'=>'hello world'));
 }
}

ログイン後にコピー

新建一个word.html

<body>
{#$content#}
</body>

ログイン後にコピー

二、CI框架+smarty模板

网上很多方法,将smarty作为一个普通的library,在使用的时候,controller代码类似于下面:

public function index()
{
  $this->load->library('smarty/Ci_smarty', '', 'smarty');
  $this->smarty->assign("title","恭喜你smarty安装成功!");
  $this->smarty->assign("body","欢迎使用smarty模板引擎");
  $arr = array(1=>'zhang',2=>'xing',3=>'wang');
  $this->smarty->assign("myarray",$arr);
  $this->smarty->display('index_2.html');
}

ログイン後にコピー

这种方法跟CI自带的使用模板的方法

代码如下:

$this->load->view();


不和谐,而且要一系列的

代码如下:

$this->smarty->assign();


语句,麻烦不说,还破坏了原本CI的简洁美,所以果断唾弃之。

那怎么保持CI加载view时的简洁美呢,答案就是覆盖Loader类的view()方法。好吧,let's begin。

2.1,条件:

到官网上现在CI框架和smarty模板。

2.2,确保CI已经能跑起来

将CI框架解压到网站跟目录下,先写一个不带smarty模板的controller输出“hello world”。

2.3,引入smarty

将smarty解压,将libs文件夹考到application/third_paty下面,并将libs重命名smarty,重命名取什么都ok了,这里就叫smarty吧。

2.4,覆盖loader类的view()方法

因为view()方法在Loader类里,所以我要覆盖Loader的view()方法。

先看看$this->load->view()是怎么工作的?CI_Controller类的构造函数里有这么一行

代码如下:

$this->load =& load_class('Loader', 'core');


load_class函数会先在application/core下面找config_item('subclass_prefix').Loader.php文件,找不到再到system/core下面找Loader.php。config_item('subclass_prefix')就是在配置文件里写的你要继承CI核心类的子类的前缀。我使用的是默认值'MY_'。找到文件后,require该文件,然后new MY_Loader(如果application/core/MY_Loader.php存在),或者是new Loader,赋值给$this->load。

在application/core下面新建一个MY_Loader.php文件

<&#63;php
define('DS', DIRECTORY_SEPARATOR);
class MY_Loader extends CI_Loader {
 public $smarty;
 public function __construct() {
  parent::__construct();
  require APPPATH.'third_party'.DS.'smarty'.DS.'smarty.class.php';
  $this->smarty = new Smarty ();
  // smarty 配置
  $this->smarty->template_dir= APPPATH.'views'.DS;//smarty模板文件指向ci的views文件夹
  $this->smarty->compile_dir = 'd:/temp/tpl_c/';
  $this->smarty->config_dir = APPPATH.'libraries/smarty/configs/';
  $this->smarty->cache_dir  = 'd:/temp/cache';
  $this->smarty->left_delimiter = '{#';
  $this->smarty->right_delimiter = '#}';
 }
 public function view($view, $vars = array(), $return = FALSE)
 {
  // check if view file exists
  $view .= config_item('templates_ext');
  $file = APPPATH.'views'.DS.$view;
  if (! file_exists ( $file ) || realpath ( $file ) === false) {
   exit( __FILE__.' '.__LINE__."<br/>View file {$file} does not exist, <br/>{$file} => {$view}");
  }
  // changed by simeng in order to use smarty debug
  foreach ( $vars as $key => $value ) {
   $this->smarty->assign ( $key, $value );
  }
  // render or return
  if ($return) {
   ob_start ();
  }
  $this->smarty->display ( $view );
  if ($return) {
   $res = ob_get_contents ();
   ob_end_clean ();
   return $res;
  }
 }
}

ログイン後にコピー

我把template_ext配置成了".html",这样就ok了。我们来验证一下吧。

2.5,验证

在controller下面建一个home.php

class Home extends CI_Controller {
 public function index() {
  $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands');
  $data['title'] = "恭喜你smarty安装成功!";
  $data['body'] = "欢迎使用smarty模板引";
  $arr = array(1=>'zhang',2=>'xing',3=>'wang');
  $data['myarray'] = $arr;
  $this->load->view('index_2', $data);
 }
}

ログイン後にコピー

在views下面建一个index_2.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <script src='<!--{$base_url}-->js/jquery.min.js' type='text/javascript' ></script>
 <link href="<!--{$base_url}-->css/login.css" rel="stylesheet" type="text/css" />
 <title>smarty安装测试</title>
</head>
<body>
<h1 id="title">{#$title#}</h1>
<p>{#$body#}</p>
<ul>
  {#foreach from=$myarray item=v#}
  <li>{#$v#}</li>
  {#/foreach#}
</ul>
</body>
</html>

ログイン後にコピー

好了,可以试试你的成果了。

三、yaf框架+smarty模板

yaf是利用引导文件Bootstrap.php来加载smarty。

3.1,使用Bootstrap

在index.php中用

代码如下:

$app->bootstrap()->run();

引入Bootstrap.php文件

3.2,在application/Bootstrap.php文件中导入smarty。

<&#63;php
class Bootstrap extends Yaf_Bootstrap_Abstract {
 public function _initSmarty(Yaf_Dispatcher $dispatcher) {
  $smarty = new Smarty_Adapter(null, Yaf_Application::app()->getConfig()->smarty);
  Yaf_Dispatcher::getInstance()->setView($smarty);
 }
}

ログイン後にコピー

3.3,添加Smarty_Adapter类

将smarty解压后放到application/library文件夹下,重命名为Smarty。在Smarty下新建Adapter.php,确保Smarty.class.php在Smarty/libs/下。Adapter.php内容:

<&#63;php
Yaf_Loader::import( "Smarty/libs/Smarty.class.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templatecompilerbase.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templatelexer.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_templateparser.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_compilebase.php");
Yaf_Loader::import( "Smarty/libs/sysplugins/smarty_internal_write_file.php");
class Smarty_Adapter implements Yaf_View_Interface
{
 /**
  * Smarty object
  * @var Smarty
  */
 public $_smarty;
 /**
  * Constructor
  *
  * @param string $tmplPath
  * @param array $extraParams
  * @return void
  */
 public function __construct($tmplPath = null, $extraParams = array()) {
  $this->_smarty = new Smarty;
  if (null !== $tmplPath) {
   $this->setScriptPath($tmplPath);
  }
  foreach ($extraParams as $key => $value) {
   $this->_smarty->$key = $value;
  }
 }
 /**
  * Return the template engine object
  *
  * @return Smarty
  */
 public function getEngine() {
  return $this->_smarty;
 }
 /**
  * Set the path to the templates
  *
  * @param string $path The directory to set as the path.
  * @return void
  */
 public function setScriptPath($path)
 {
  if (is_readable($path)) {
   $this->_smarty->template_dir = $path;
   return;
  }
  throw new Exception('Invalid path provided');
 }
 /**
  * Retrieve the current template directory
  *
  * @return string
  */
 public function getScriptPath()
 {
  return $this->_smarty->template_dir;
 }
 /**
  * Alias for setScriptPath
  *
  * @param string $path
  * @param string $prefix Unused
  * @return void
  */
 public function setBasePath($path, $prefix = 'Zend_View')
 {
  return $this->setScriptPath($path);
 }
 /**
  * Alias for setScriptPath
  *
  * @param string $path
  * @param string $prefix Unused
  * @return void
  */
 public function addBasePath($path, $prefix = 'Zend_View')
 {
  return $this->setScriptPath($path);
 }
 /**
  * Assign a variable to the template
  *
  * @param string $key The variable name.
  * @param mixed $val The variable value.
  * @return void
  */
 public function __set($key, $val)
 {
  $this->_smarty->assign($key, $val);
 }
 /**
  * Allows testing with empty() and isset() to work
  *
  * @param string $key
  * @return boolean
  */
 public function __isset($key)
 {
  return (null !== $this->_smarty->get_template_vars($key));
 }
 /**
  * Allows unset() on object properties to work
  *
  * @param string $key
  * @return void
  */
 public function __unset($key)
 {
  $this->_smarty->clear_assign($key);
 }
 /**
  * Assign variables to the template
  *
  * Allows setting a specific key to the specified value, OR passing
  * an array of key => value pairs to set en masse.
  *
  * @see __set()
  * @param string|array $spec The assignment strategy to use (key or
  * array of key => value pairs)
  * @param mixed $value (Optional) If assigning a named variable,
  * use this as the value.
  * @return void
  */
 public function assign($spec, $value = null) {
  if (is_array($spec)) {
   $this->_smarty->assign($spec);
   return;
  }
  $this->_smarty->assign($spec, $value);
 }
 /**
  * Clear all assigned variables
  *
  * Clears all variables assigned to Zend_View either via
  * {@link assign()} or property overloading
  * ({@link __get()}/{@link __set()}).
  *
  * @return void
  */
 public function clearVars() {
  $this->_smarty->clear_all_assign();
 }
 /**
  * Processes a template and returns the output.
  *
  * @param string $name The template to process.
  * @return string The output.
  */
 public function render($name, $value = NULL) {
  return $this->_smarty->fetch($name);
 }
 public function display($name, $value = NULL) {
  echo $this->_smarty->fetch($name);
 }
}

ログイン後にコピー

3.4,smarty配置文件。

再来看看我们的conf/application.ini文件

[common]
application.directory = APP_PATH "/application"
application.dispatcher.catchException = TRUE
application.view.ext="tpl"
[smarty : common]
;configures for smarty
smarty.left_delimiter = "{#"
smarty.right_delimiter = "#}"
smarty.template_dir  = APP_PATH "/application/views/"
smarty.compile_dir  = '/data1/www/cache/'
smarty.cache_dir  = '/data1/www/cache/'
[product : smarty]

ログイン後にコピー

3.5,验证

新建一个controller,添加方法:

public function twoAction() {
  $this->getView()->assign('content', 'hello World');
}

ログイン後にコピー

新建一个模板two.tpl

<html>
<head>
<title>A Smarty Adapter Example</title>
</head>
<body>
{#$content#}
</body>
</html>

ログイン後にコピー

希望本文所述对大家PHP程序设计有所帮助。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Java フレームワークの商用サポートの費用対効果を評価する方法 Java フレームワークの商用サポートの費用対効果を評価する方法 Jun 05, 2024 pm 05:25 PM

Java フレームワークの商用サポートのコスト/パフォーマンスを評価するには、次の手順が必要です。 必要な保証レベルとサービス レベル アグリーメント (SLA) 保証を決定します。研究サポートチームの経験と専門知識。アップグレード、トラブルシューティング、パフォーマンスの最適化などの追加サービスを検討してください。ビジネス サポートのコストと、リスクの軽減と効率の向上を比較検討します。

PHP フレームワークの学習曲線は他の言語フレームワークと比較してどうですか? PHP フレームワークの学習曲線は他の言語フレームワークと比較してどうですか? Jun 06, 2024 pm 12:41 PM

PHP フレームワークの学習曲線は、言語熟練度、フレームワークの複雑さ、ドキュメントの品質、コミュニティのサポートによって異なります。 PHP フレームワークの学習曲線は、Python フレームワークと比較すると高く、Ruby フレームワークと比較すると低くなります。 Java フレームワークと比較すると、PHP フレームワークの学習曲線は中程度ですが、開始までの時間は短くなります。

PHP フレームワークの軽量オプションはアプリケーションのパフォーマンスにどのような影響を与えますか? PHP フレームワークの軽量オプションはアプリケーションのパフォーマンスにどのような影響を与えますか? Jun 06, 2024 am 10:53 AM

軽量の PHP フレームワークは、サイズが小さくリソース消費が少ないため、アプリケーションのパフォーマンスが向上します。その特徴には、小型、高速起動、低メモリ使用量、改善された応答速度とスループット、および削減されたリソース消費が含まれます。 実際のケース: SlimFramework は、わずか 500 KB、高い応答性と高スループットの REST API を作成します。

実際の開発における C++ テンプレートの一般的な用途は何ですか? 実際の開発における C++ テンプレートの一般的な用途は何ですか? Jun 05, 2024 pm 05:09 PM

C++ テンプレートは、コンテナ クラス テンプレート、アルゴリズム テンプレート、汎用関数テンプレート、メタプログラミング テンプレートなど、実際の開発で広く使用されています。たとえば、汎用の並べ替えアルゴリズムを使用して、さまざまな種類のデータの配列を並べ替えることができます。

さまざまなアプリケーションシナリオに最適な Golang フレームワークを選択する方法 さまざまなアプリケーションシナリオに最適な Golang フレームワークを選択する方法 Jun 05, 2024 pm 04:05 PM

アプリケーションのシナリオに基づいて最適な Go フレームワークを選択します。アプリケーションの種類、言語機能、パフォーマンス要件、エコシステムを考慮します。一般的な Go フレームワーク: Jin (Web アプリケーション)、Echo (Web サービス)、Fiber (高スループット)、gorm (ORM)、fasthttp (速度)。実際のケース: REST API (Fiber) の構築とデータベース (gorm) との対話。フレームワークを選択します。主要なパフォーマンスには fasthttp、柔軟な Web アプリケーションには Jin/Echo、データベース インタラクションには gorm を選択してください。

golang フレームワーク開発の実践的な詳細な説明: 質疑応答 golang フレームワーク開発の実践的な詳細な説明: 質疑応答 Jun 06, 2024 am 10:57 AM

Go フレームワーク開発における一般的な課題とその解決策は次のとおりです。 エラー処理: 管理にはエラー パッケージを使用し、エラーを一元的に処理するにはミドルウェアを使用します。認証と認可: サードパーティのライブラリを統合し、資格情報を確認するためのカスタム ミドルウェアを作成します。同時処理: ゴルーチン、ミューテックス、チャネルを使用してリソース アクセスを制御します。単体テスト: 分離のために getest パッケージ、モック、スタブを使用し、十分性を確保するためにコード カバレッジ ツールを使用します。デプロイメントとモニタリング: Docker コンテナを使用してデプロイメントをパッケージ化し、データのバックアップをセットアップし、ログ記録およびモニタリング ツールでパフォーマンスとエラーを追跡します。

Golang フレームワークの学習プロセスでよくある誤解は何ですか? Golang フレームワークの学習プロセスでよくある誤解は何ですか? Jun 05, 2024 pm 09:59 PM

Go フレームワークの学習には、フレームワークへの過度の依存と柔軟性の制限という 5 つの誤解があります。フレームワークの規則に従わない場合、コードの保守が困難になります。古いライブラリを使用すると、セキュリティと互換性の問題が発生する可能性があります。パッケージを過度に使用すると、コード構造が難読化されます。エラー処理を無視すると、予期しない動作やクラッシュが発生します。

Golang フレームワークのパフォーマンス比較: 賢明な選択を行うための指標 Golang フレームワークのパフォーマンス比較: 賢明な選択を行うための指標 Jun 05, 2024 pm 10:02 PM

Go フレームワークを選択する場合、主要業績評価指標 (KPI) には、応答時間、スループット、同時実行性、リソース使用量が含まれます。フレームワークの KPI をベンチマークして比較することで、開発者は、予想される負荷、パフォーマンスが重要なセクション、リソースの制約を考慮しながら、アプリケーションのニーズに基づいて情報に基づいた選択を行うことができます。

See all articles