This article describes the example of yii, CI, yaf framework smarty template usage method. Share it with everyone for your reference, the details are as follows:
Recently, I have been tossing the performance test of the framework, which needs to test the performance of each template in conjunction with smarty, so I have gone through a lot of it and now I will summarize it. I have written about the kohana framework smarty template before, so I won’t repeat it here.
1. yii framework smarty template
yii covers the viewRenderer component.
1.1, download the yii framework and unzip it, download the smarty framework and unzip it, copy the smarty/libs folder to the yii framework application/protected/vendors, and rename smarty.
1.2, yii configuration file 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', ) )
Where batman is the alias I have defined in index.php.
Yii::setPathOfAlias('batman', dirname(__FILE__)); Yii::import("batman.protected.vendors.*"); define('APP_DIR', dirname(__FILE__).'/protected/');
1.3, create a new SmartyViewRender.php under protected/extensions/
<?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, verified
Create a new HelloController.php
<?php class HelloController extends Controller { public function actionWorld() { $this->render('world', array('content'=>'hello world')); } }
Create a new word.html
<body> {#$content#} </body>
2. CI framework smarty template
There are many methods on the Internet to use smarty as an ordinary library. When using it, the controller code is similar to the following:
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'); }
This method is similar to the method of using templates that comes with CI
Copy code The code is as follows: $this->load->view();
It’s disharmonious and requires a series of
Copy code The code is as follows: $this->smarty->assign();
The statement is not only troublesome, but also destroys the simplicity and beauty of the original CI, so I decisively discard it.
So how to keep the simplicity and beauty of CI loading views? The answer is to override the view() method of the Loader class. Okay, let's begin.
2.1, conditions:
Go to the official website to download the CI framework and smarty template.
2.2, make sure CI is running
Extract the CI framework to the website and directory, first write a controller without smarty template to output "hello world".
2.3, introduce smarty
Unzip smarty, move the libs folder to application/third_paty, and rename libs to smarty. Whatever you rename is ok, just call it smarty here.
2.4, override the view() method of the loader class
Because the view() method is in the Loader class, I have to override the view() method of Loader.
Let’s first look at how $this->load->view() works? There is this line in the constructor of the CI_Controller class
Copy code The code is as follows: $this->load =& load_class('Loader', 'core');
The load_class function will first look for the config_item('subclass_prefix').Loader.php file under application/core. If it cannot find it, then look for Loader.php under system/core. config_item('subclass_prefix') is the prefix of the subclass that you want to inherit from the CI core class written in the configuration file. I'm using the default value 'MY_'. After finding the file, require the file, then new MY_Loader (if application/core/MY_Loader.php exists), or new Loader, assign the value to $this->load.
Create a new MY_Loader.php file under application/core
<?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; } } }
I configured template_ext to ".html", so it's ok. Let’s verify it.
2.5, verified
Create a home.php under the controller
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); } }
Create an index_2.html under views
<!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>{#$title#}</h1> <p>{#$body#}</p> <ul> {#foreach from=$myarray item=v#} <li>{#$v#}</li> {#/foreach#} </ul> </body> </html>
Okay, you can try your results.
3. yaf framework smarty template
yaf uses the boot file Bootstrap.php to load smarty.
3.1, using Bootstrap
Use
in index.php
Copy code The code is as follows: $app->bootstrap()->run();
Introduce the Bootstrap.php file
3.2, import smarty in the application/Bootstrap.php file.
<?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, add Smarty_Adapter class
Unzip smarty and put it in the application/library folder and rename it to Smarty. Create a new Adapter.php under Smarty and ensure that Smarty.class.php is under Smarty/libs/. Adapter.php content:
<?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 configuration file.
Let’s take a look at our conf/application.ini file
[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, verified
Create a new controller and add method:
public function twoAction() { $this->getView()->assign('content', 'hello World'); }
Create a new template two.tpl
<html> <head> <title>A Smarty Adapter Example</title> </head> <body> {#$content#} </body> </html>
I hope this article will be helpful to everyone in PHP programming.