Yii,ci,yaf Framework +smarty Template use method _php instance

Source: Internet
Author: User
Tags mixed php class php define php programming vars smarty template yii

The example of this article describes the YII,CI,YAF framework +smarty template usage. Share to everyone for your reference, specific as follows:

Recently toss the framework of performance testing, which needs to test each template with smarty performance, so toss a bucket, now summed up. The Kohana framework +smarty template has been written before and is not repeated here.

A, Yii framework +smarty template

Yii is covered with viewrenderer components.

1.1, download the YII framework and unzip, download the Smarty framework and unpack, copy the Smarty/libs folder under the Yii frame application/protected/vendors, and rename Smarty.

1.2,yii configuration file main.php

' Components ' =>array ('
 viewrenderer ' => Array (
  ' class ' => ') Batman.protected.extensions.SmartyViewRender ',
  //Here for the Smarty supported attribute
  ' 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 that 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 '); The Public function RenderFile ($context, $file, $data, $return) {foreach ($data as $key => $value) $this-&GT;_SM
  Arty->assign ($key, $value);
  $return = $this->_smarty->fetch ($file);
  if ($return) return $return;
Else    Echo $return;

 }
}

1.4, verify

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>

Ii. CI Framework +smarty Template

There are many ways to use smarty as an ordinary library, and when used, the controller code resembles the following:

Public Function Index ()
{
  $this->load->library (' Smarty/ci_smarty ', ', ', ' smarty ');
  $this->smarty->assign ("title", "Congratulations you smarty installation success!" ");
  $this->smarty->assign ("Body", "Welcome to use Smarty template Engine");
  $arr = Array (1=> ' Zhang ',2=> ' Xing ',3=> ' Wang ');
  $this->smarty->assign ("MyArray", $arr);
  $this->smarty->display (' index_2.html ');
}

This method is used with the method of using the template with CI

Copy Code code as follows:
$this->load->view ();

Disharmony, and a series of
Copy Code code as follows:
$this->smarty->assign ();

Statement, trouble not to say, but also destroyed the original CI concise beauty, so resolute contempt.

How to maintain the simplicity of CI loading view, the answer is to overwrite the view () method of the loader class. Well, let's begin.

2.1, Conditions:

To the official web now CI frames and smarty templates.

2.2, make sure CI is ready to run.

Unzip the CI frame to the website and directory, first write a controller output "Hello World" without smarty template.

2.3, introduce Smarty

Will smarty decompression, will libs folder to Application/third_paty below, and will libs rename smarty, rename take what all OK, here is called Smarty Bar.

2.4, overriding the view () method of the loader class

Because the view () method is in the loader class, I want to overwrite the loader view () method.

First look at how $this->load->view () is working? There is one line in the constructor of the Ci_controller class

Copy Code code as follows:
$this->load =& load_class (' Loader ', ' core ');

The Load_class function will first find Config_item (' Subclass_prefix ') under the Application/core. loader.php file, can not find the next system/core to find loader.php. Config_item (' Subclass_prefix ') is the prefix written in the configuration file that you want to inherit from the subclass of the CI core class. I'm using the default value ' My_ '. After the file is found, require the file, and then the new My_loader (if application/core/my_loader.php exists), or the new Loader, assigns 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 configuration $this->smarty->template_dir= apppath. ' Views '.
  The Ds;//smarty template file points to Ci's views folder $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 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 the Template_ext to ". html", so that's OK. Let's test it out.

2.5, verify

Build 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 '] = "Congratulations on your Smarty installation success!" ";
  $data [' body '] = "Welcome to use Smarty Template primer";
  $arr = Array (1=> ' Zhang ',2=> ' Xing ',3=> ' Wang ');
  $data [' myarray '] = $arr;
  $this->load->view (' Index_2 ', $data);
 }


Build a index_2.html below the views

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
 
 

Well, you can try your results.

Iii. YAF Framework +smarty Template

YAF is to load the smarty using the boot file bootstrap.php.

3.1, using bootstrap

In index.php

Copy Code code as follows:
$app->bootstrap ()->run ();

Introducing bootstrap.php Files

3.2, import the 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 the Smarty and place it in the Application/library folder and rename it to Smarty. Create a new adapter.php under Smarty to make sure 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 engineObject * * @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 () {retur
 N $this->_smarty->template_dir; /** * Alias for Setscriptpath * * @param string $path * @param string $prefix unused * @return void */Pub
 Lic function Setbasepath ($path, $prefix = ' Zend_view ') {return $this->setscriptpath ($path); /** * Alias for Setscriptpath * * @param string $path * @param string $prefix unused * @return void */Pub Lic 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 fun
 Ction __isset ($key) {return (null!== $this->_smarty->get_template_vars ($key)); /** * allows unset () on the 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 * a
  n 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->assi
   GN ($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, verify

To create a new controller, add a method:

Public Function twoaction () {
  $this->getview ()->assign (' content ', ' Hello World ');
}

Create a new template Two.tpl

 
 

I hope this article will help you with your PHP programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.