Cake PHP + Smarty = un gâteau aux smarties

Cake PHP + Smarty = un gâteau aux smarties

sommaire :

  1. Installation de smarty dans cake php
  2. Configuration Smarty
 

Dans ce tutoriel, nous allons voir comment utiliser smarty avec cake php pour ne plus avoir des templates moches en .ctp

Installation de smarty dans cake php :

Vous avez bien entendu téléchargé smarty depuis le site officiel ainsi que cake php.

Dans monProjet/vendors, créez le dossier smarty. Dedans, vous y mettrez:

cakephp smarty

cakephp smarty

Vous trouverez ces fichiers et dossiers dans le package smarty que vous avez téléchargé.

Dans app/views, vous créerez ce fichier smart.php, il contiendra le script suivant :

/**
* Include Smarty. By default expects it at ( VENDORS.'smarty'.DS.'Smarty.class.php' )
*/

/**
* CakePHP Smarty view class
*
* This class will allow using Smarty with CakePHP
*
* @version      1.1.0.0
* @package      cake
* @subpackage   cake.app.views
* @since        CakePHP v 1.2
*/
class SmartyView extends View
{
/**
* SmartyView constructor
*
* @param  $controller instance of calling controller
*/
function __construct (&$controller)
{
parent::__construct($controller);
App::import('Vendor', 'Smarty', array('file' => 'smarty'.DS.'Smarty.class.php'));
$this->Smarty = &new Smarty();
// requires views be in a 'smarty' subdirectory, you can remove this limitation if you aren't using other inherited views that use .tpl as the extension
//$this->subDir = 'smarty'.DS;
$this->ext= '.tpl';
$this->Smarty->plugins_dir[] = VIEWS.'smarty_plugins'.DS;
$this->Smarty->compile_dir = TMP.'smarty'.DS.'compile'.DS;
$this->Smarty->cache_dir = TMP.'smarty'.DS.'cache'.DS;
$this->Smarty->error_reporting = 'E_ALL & ~E_NOTICE';
$this->Smarty->debugging = true;
}

/**
* Overrides the View::_render()
* Sets variables used in CakePHP to Smarty variables
*
* @param string $___viewFn
* @param string $___data_for_view
* @param string $___play_safe
* @param string $loadHelpers
* @return rendered views
*/
function _render($___viewFn, $___data_for_view, $___play_safe = true, $loadHelpers = true)
{
if ($this->helpers != false && $loadHelpers === true)
{
$loadedHelpers =  array();
$loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);

foreach(array_keys($loadedHelpers) as $helper)
{
$replace = strtolower(substr($helper, 0, 1));
$camelBackedHelper = preg_replace('/\w/', $replace, $helper, 1);

${$camelBackedHelper} =& $loadedHelpers[$helper];
if(isset(${$camelBackedHelper}->helpers) && is_array(${$camelBackedHelper}->helpers))
{
foreach(${$camelBackedHelper}->helpers as $subHelper)
{
${$camelBackedHelper}->{$subHelper} =& $loadedHelpers[$subHelper];
}
}
$this->loaded[$camelBackedHelper] = (${$camelBackedHelper});
$this->Smarty->assign_by_ref($camelBackedHelper, ${$camelBackedHelper});
}
}

$this->register_functions();

foreach($___data_for_view as $data => $value)
{
if(!is_object($data))
{
$this->Smarty->assign($data, $value);
}
}
$this->Smarty->assign_by_ref('view', $this);
return $this->Smarty->fetch($___viewFn);
}

/**
* Returns layout filename for this template as a string.
*
* @return string Filename for layout file (.ctp).
* @access private
*/
function _getLayoutFileName() {
if (isset($this->webservices) && !is_null($this->webservices)) {
$type = strtolower($this->webservices) . DS;
} else {
$type = null;
}

if (isset($this->plugin) && !is_null($this->plugin)) {
if (file_exists(APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'layouts' . DS . $this->layout . $this->ext)) {
$layoutFileName = APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'layouts' . DS . $this->layout . $this->ext;
return $layoutFileName;
}
}
$paths = Configure::getInstance();

foreach($paths->viewPaths as $path) {
if (file_exists($path . 'layouts' . DS . $this->subDir . $type . $this->layout . $this->ext)) {
$layoutFileName = $path . 'layouts' . DS . $this->subDir . $type . $this->layout . $this->ext;
return $layoutFileName;
}
}

// added for .ctp viewPath fallback
foreach($paths->viewPaths as $path) {
if (file_exists($path . 'layouts' . DS  . $type . $this->layout . '.ctp')) {
$layoutFileName = $path . 'layouts' . DS . $type . $this->layout . '.ctp';
return $layoutFileName;
}
}

if($layoutFileName = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . 'layouts' . DS . $type . $this->layout . '.ctp')) {
} else {
$layoutFileName = LAYOUTS . $type . $this->layout.$this->ext;
}
return $layoutFileName;
}

/**
* Returns filename of given action's template file (.tpl) as a string.
* CamelCased action names will be under_scored! This means that you can have
* LongActionNames that refer to long_action_names.ctp views.
*
* @param string $action Controller action to find template filename for
* @return string Template filename
* @access protected
*/
function _getViewFileName($name = null) {
$subDir = null;

if (!is_null($this->webservices)) {
$subDir = strtolower($this->webservices) . DS;
}
if (!is_null($this->subDir)) {
$subDir = $this->subDir . DS;
}

if ($name === null) {
$name = $this->action;
}

if (strpos($name, '/') === false && strpos($name, '..') === false) {
$name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
} elseif (strpos($name, '/') !== false) {
if ($name{0} === '/') {
if (is_file($name)) {
return $name;
}
$name = trim($name, '/');
} else {
$name = $this->viewPath . DS . $subDir . $name;
}
if (DS !== '/') {
$name = implode(DS, explode('/', $name));
}
} elseif (strpos($name, '..') !== false) {
$name = explode('/', $name);
$i = array_search('..', $name);
unset($name[$i - 1]);
unset($name[$i]);
$name = '..' . DS . implode(DS, $name);
}

$paths = $this->_paths($this->plugin);
foreach ($paths as $path) {
if (file_exists($path . $name . $this->ext)) {
return $path . $name . $this->ext;
} elseif (file_exists($path . $name . '.ctp')) {
return $path . $name . '.ctp';
} elseif (file_exists($path . $name . '.thtml')) {
return $path . $name . '.thtml';
}
}

return $this->_missingView($paths[0] . $name . $this->ext, 'missingView');
}

/**
* checks for existence of special method on loaded helpers, invoking it if it exists
* this allows helpers to register smarty functions, modifiers, blocks, etc.
*/
function register_functions() {
foreach(array_keys($this->loaded) as $helper) {

if (method_exists($this->loaded[$helper], '_register_smarty_functions')) {
$this->loaded[$helper]->_register_smarty_functions($this->Smarty);
}
}
}
}

Vous créerez aussi app_controller.php dans app/controllers, il contiendra :


class AppController extends Controller {

//pour utliser smarty en moteur de templates
var $view = 'Smarty';
}

Configuration Smarty

Les fichiers venant d’être créés vous servirons à configurer smarty et utiliser smarty pour les vues (templates).

Utilisation :
les lignes qui suivent servent à configurer smarty :

$this->ext= '.tpl';
$this->Smarty->plugins_dir[] = VIEWS.'smarty_plugins'.DS;
$this->Smarty->compile_dir = TMP.'smarty'.DS.'compile'.DS;
$this->Smarty->cache_dir = TMP.'smarty'.DS.'cache'.DS;
$this->Smarty->error_reporting = 'E_ALL & ~E_NOTICE';
$this->Smarty->debugging = true;

Vous configurez ainsi :

  • le chemin des plugins smarty
  • le chemin des fichiers compilés
  • le chemin de cache smarty

Vous devez créer les dossier smarty_plugins, compile (/app/tmp/smarty/compile) et cache (/app/tmp/smarty/cache) dans les répertoires correspondant aux différents chemins que vous aurez choisi.

Vous avez aussi configuré le débuggage et le système d’erreur smarty.

Dans l’exemple vu dans l’installation et l’utilisation de cake php, nous avons vu comment créer une page.

La méthode ne change pas, et la méthode d’assignation non plus.

Vous devez simplement créer les templates avec l’extension sélectionnée pour paramétrer smarty et dans le template, vous devez utiliser la syntaxe de smarty pour l’affichage.

Vous devez créer mapage.tpl et utiliser une syntaxe de ce type {$sMaVariableVue}
non pas echo $sMaVariableVue;

Note de l'article




1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, moyenne: 4,67 max : 5)
Loading ... Loading ...

Donner votre avis :