Smarty Forum Index Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon.

Smarty + ZendFramework: working, 'complete' code

 
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Frameworks
View previous topic :: View next topic  
Author Message
OpenMacNews
Smarty Rookie


Joined: 03 Aug 2004
Posts: 34
Location: Floating on Io's Methane Seas ...

PostPosted: Fri May 05, 2006 8:09 pm    Post subject: Smarty + ZendFramework: working, 'complete' code Reply with quote

hi all,

my goal was to get Zend Framework (ZF) to behave with Smarty, using:

Code:

   Zend Framework
   Smarty as Templating System --> extending the Zend_View class
   Smarty {ClipCache} add-on for granular, in-template cache management
   ezComponents platform --> use its array-based configuration class
                             ( at least until 'Zend_Config' is developed ... )



so, of course, installation prereq's are:

Code:

   Smarty        --> http://smarty.php.net
   ZendFramework --> http://framework.zend.com
   ezComponents  --> http://ez.no/products/ez_components


NOTE: join/read the mailing lists!

also, fwiw, my env is:
Code:

   Apache/2.2.3-dev
      Server loaded:  APR 1.2.8-dev, APR-Util 1.2.8-dev
      Compiled using: APR 1.2.8-dev, APR-Util 1.2.8-dev
      Architecture:   32-bit
      Server MPM:     Worker
   PHP
      Version => 5.1.4
      Debug Build => no
      Thread Safety => enabled
      Zend Memory Manager => enabled
      eAccelerator support => enabled
         Version => 0.9.5-beta2, r209
   Mac OSX
      System => Darwin server 8.6.0 Darwin Kernel Version 8.6.0:
      Tue Mar  7 16:58:48 PST 2006; root:xnu-792.6.70.obj~1/RELEASE_PPC Power Macintosh



reading/references/resources *heavily* used:

Code:

   "Zend Framework: A Practical Tutorial"
    http://www.phparch.com/zftut/

   "Zend Framework: Using Smarty As Template Engine"
   http://kpumuk.info/php/zend-framework-using-smarty-as-template-engine/

   "INTEGRATING SMARTY WITH THE ZEND FRAMEWORK"
    http://devzone.zend.com/node/view/id/120

   "INTEGRATING SMARTY AND EZ COMPONENTS WITH THE ZEND FRAMEWORK"
    http://devzone.zend.com/node/view/id/156

   ezComponents configuration class
    http://ez.no/doc/components/view/latest/(file)/introduction_Configuration.html

   "Smartest Smarty Practices"
    http://smarty.incutio.com/?page=SmartestSmartyPractices

   Smarty clipcache
    http://www.phpinsider.com/smarty-forum/viewtopic.php?t=1343&start=23

   PHP Wiki re: Zend Framework
    http://wiki.cc/php/Special:Search?search=zend&go=Go

   "Zend Framework: Thoughts about Zend_Config"
    http://kpumuk.info/php/zend-framework-thoughts-about-zend_config/

   "Akrabat_Config (Take Three!)"
    http://www.akrabat.com/2006/04/10/akrabat_config-three/





NOTES:
since i'm apparently having a conversation with myself Wink , i'll just keep mod'ing this as i make progress ...

5/10/06 15:10:12
added missing register_clipcache(); call

5/10/06 10:27:36
added suggestion (Simon M.) from the ZF list --> changes to Smarty.php.
adds capability to simply using:
. $view->assign($vars);
from a controller, now also:
. $view->myvar1 = $myvar1;
. $view->myvar2 = $myvar2;
and render in Smarty *.tpl as:
. {$myvar1} and {$myvar2}
===
+ a little index.php cleanup ...

5/9/06 22:48:41
added the var pass of ScriptPath to $smarty object; fixes the full path problem.
added index.php here, apparently forgotten!
fixed a couple of typos.

5/7/06 12:45:12
just posting code that works now ... leave the discussion for the lists.
changed my mind, using ezComponents config, but Array-based *not* .ini-based
.tpl's now displaying correctly via Zend_View class extension
.tpl's accessible via short-url nav thru ZF FrontController
some pending issues with ZF vs Smarty path context ...

5/5/06 20:22:22 added another tutorial references, couple of corrections/additions to the recommended/required mod_rewrite conf

5/5/06 15:19:39 switched to "$view", rather than "$smarty" object-name for consistency

5/5/06 14:55:51 got the class definition in the extended Zend_View_Abstract straightened out, and smarty instantiation no longer firing an error


for the purposes of this proj, my site layout is:

Code:

/webapps/
   tools/
      smarty/
         libs/
      zend_framework/
         library/
      ezcomponents/
   resources/
      cache/
      configs/
         siteEnv.php
      fonts/
      includes/
         Smarty_ClipCache.class.php
         frontpage/
            data.inc
      plugins/
         function.include_clipcache.php
         prefilter.clipcache.php
      scripts/
      templates/
         frontpage.tpl
         loginpage.tpl
      templates_c/
   zf_controllers/
      IndexController.php
      IntroController.php
   zf_classes/
      MyTest/
         View/
            Smarty.php
   document_root/
      index.php
      images/
      css/
         base.css
         frontpage/
            frontpage.css
      includes/



here's the code that's working for me, in its entirety (except for the .tpl's, which can be as you like, of course).

it's basically uncommented -- you can get lots of comments/explanations at the references i've included. *here*, however, it's -- i'm fairly certain -- complete.

enjoy, and feedback with problems!

cheers,

richard


index.php
Code:
========================================================
<?php

session_start();

$tools_root  = '/webapps/tools';
$site_root   = '/webapps';

ini_set('include_path',
           $site_root
   . ":" . $site_root  . '/resources/templates'
   . ":" . $tools_root . '/ezcomponents'
   . ":" . $tools_root . '/zend_framework/library'
   . ":" . $site_root  . '/zf_classes'
   . ":" . ini_get('include_path')
);

// PHP
require_once('PEAR.php');

// ezComponents --> autoload
require_once('Base/src/base.php');

function __autoload($class)
   {
      if ('ezc' == substr($class, 0, 3))
         {
            ezcBase::autoload($class);
         }
      else
         {
            Zend::loadClass($class);
         }
   }

// Zend Framework
require_once('Zend.php');
Zend::loadClass('Zend_View_Abstract');


// retrieve ezComonents configuration
$reader = new ezcConfigurationArrayReader();
$reader->init($site_root.'/resources/configs', 'siteEnv' );
$config = $reader->load();

Zend::register('config', $config);
$config = Zend::registry('config');

$viewConf = array(
  'scriptPath' => array($config->getSetting('zf', 'view_dir'),
                        $config->getSetting('sm', 'template_dir')
                       )
                 );
$smConf = $config->getSettingsInGroup('sm');

// instantiate Smarty object
Zend::loadClass('MyTest_View_Smarty');
$smarty = new MyTest_View_Smarty($viewConfig,$smConf);
$smarty->addScriptPath($viewConf['scriptPath']);
Zend::register('smarty', $smarty);

// pass to FrontController
Zend::loadClass('Zend_Controller_Front');
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory($config->getSetting('zf', 'controller_dir'));
$controller->dispatch();

?>
========================================================



frontpage.tpl
Code:
========================================================
... ( whatever ) ...
<style type="text/css" media="all">
   @import "/css/base.css";
   @import "/css/<ste: $this_section :ste>/<ste: $this_section :ste>.css";
</style>
...
... ( whatever ) ...
========================================================


loginpage.tpl
Code:
========================================================
... ( whatever ) ...

you should bbe able to use {clipcache}{/clipcache} sections in here!
========================================================


indexController.php
Code:
========================================================
<?php
   Zend::loadClass('Zend_Controller_Action');
   class IndexController extends Zend_Controller_Action
   {
      public function indexAction()
      {
         $smarty = Zend::registry('smarty');
         $smarty->output('loginpage.tpl');
      }
      public function noRouteAction()
      { $this->_redirect('/'); }
   }
?>
========================================================


introController.php
Code:
========================================================
<?php

Zend::loadClass('Zend_Controller_Action');

class IntroController extends Zend_Controller_Action
{
   public function indexAction()
   { $this->_redirect('/'); }

   public function welcomeAction()
   {
      $smarty = Zend::registry('smarty');
      $this_section = 'frontpage';

   // an example of including some data ...
      include('resources/includes/'.$this_section.'/data.inc');

   // an example of passing a variable to the template ...
      $smarty->assign('this_section',$this_section);
      $smarty->output('frontpage.tpl');
   }

// create noRouteAction() method for nonexsitent controllers
   public function noRouteAction()
   { $this->_redirect('/'); }

// create __call() method to handle requests for undefined actions
   public function __call($action, $arguments)
   { $this->_redirect('/'); }
}
?>
========================================================


Smarty.php
Code:
========================================================
<?php

require_once('Smarty.class.php');
require_once('resources/includes/Smarty_ClipCache.class.php');

class MyTest_View_Smarty extends Zend_View_Abstract
{
   private $_smarty = false;
    private $_vars = array();

/**
 * http://devzone.zend.com/node/view/id/156
 * amend constructor to accept 2 params with settings data:
 * one for the parent class and one for Smarty.
 */
public function __construct($viewConf = array(), $smConf = array())
   {
      parent::__construct($viewConf);

        $this->_smarty = new Smarty_ClipCache();

      foreach($smConf as $key => $value)
      {
         $this->_smarty->$key = $value;
      }
   }

   /**
    * Directly assigns a variable to the view script.
    * VAR names may not be prefixed with '_'.
    *   @param string $key The variable name.
    *   @param mixed $val The variable value.
    *   @return void
    */
   public function __set($key, $val)
   {
      /**
       * @todo exception?
       */
      if ($key[0] != '_') {
         $this->_vars[$key] = $val;
      }
   }

   /**
    * Retrieves an assigned variable.
    * VAR names may not be prefixed with '_'.
    *   @param string $key The variable name.
    *   @return mixed The variable value.
    */
   public function __get($key)
   {
      /**
       * @todo exception?
       */
      if ($key[0] != '_') {
         return isset($this->_vars[$key]) ? $this->_vars[$key] : null;
      }
   }

   public function render($name)
   {
      echo parent::render($name);
   }
   
   public function fetch($name)
   {
      return parent::render($name);
   }

   protected function _run($template)
   {
      $this->_smarty->assign('smarty', $this);
      $this->_smarty->register_clipcache();
      $this->_smarty->display($template);
   }


   public function assign($var)
   {
      if (is_string($var))
      {
         $value = @func_get_arg(1);
         $this->_smarty->assign($var, $value);
      }
      elseif (is_array($var))
      {
         foreach ($var as $key => $value)
         {
            $this->_smarty->assign($key, $value);
         }
      }
      else
      {
         throw new Zend_View_Exception('assign() expects a string or array, got '.gettype($var));
      }
   }


   public function escape($var)
   {
      if (is_string($var))
      {
         return parent::escape($var);
      }
      elseif (is_array($var))
      {
         foreach ($var as $key => $val)
         {
            $var[$key] = $this->escape($val);
         }
         return $var;
      }
      else
      {
         return $var;
      }
   }


   public function output($name)
   {
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("Cache-Control: no-cache");
      header("Pragma: no-cache");
      header("Cache-Control: post-check=0, pre-check=0", FALSE);
      print parent::render($name);
   }


   public function isCached($template)
   {
      if ($this->_smarty->is_cached($template))
      {
         return true;
      }
      return false;
   }


   public function setCaching($caching)
   {
      $this->_smarty->caching = $caching;
   }
}
?>
========================================================


siteEnv.php
Code:
========================================================
<?php

$tools_root  = '/webapps/tools';
$site_root   = '/webapps';

return array (
'settings' => array (

   'site' => array (
      'fonts_dir'         => $site_root.'/resources/fonts/ttf',
      'includes_dir'      => $site_root.'/resources/includes',
      'scripts_dir'      => $site_root.'/resources/scripts',
      'images_dir'      => $site_root.'/document_root/images',
      'styles_dir'      => $site_root.'/document_root/css',
   ),

   'sm' => array (
      'debugging'         => 0,
      'left_delimiter'   => "{",
      'right_delimiter'   => "}",
      'compile_check'      => 1,
      'force_compile'      => 1,
      'caching'         => 1,
      'cache_lifetime'   => 20,
      'SMARTY_DIR'      => $tools_root.'/smarty/libs/',
      'SMARTY_CORE_DIR'    => $tools_root.'/smarty/libs/internals/',
      'template_dir'      => $site_root.'/resources/templates',
      'compile_dir'      => $site_root.'/resources/templates_c',
      'cache_dir'         => $site_root.'/resources/cache',
      'config_dir'      => $site_root.'/resources/configs',
      'plugins_dir'      => array('plugins',
                               $site_root.'/resources/plugins',
                             ),
//      'cache_handler_func'   => smarty_cache_eaccelerator,
   ),

   'zf' => array (
      'application_dir'   => $tools_root.'/zend_framework/library',
      'controller_dir'   => $site_root.'/zf_controllers',
      'model_dir'         => $site_root.'/zf_classes',
      'view_dir'         => array($site_root.'/resources/temlpates',
                             ),
   ),
),

'comments' => array (

   'site' => array (
      '#' => 'site layout settings',
   ),

   'sm' => array (
      '#' => 'settings for Smarty',
      'compile_check'   => 'FALSE for production use',
      'force_compile'   => 'FALSE for production use',
   ),

   'zf' => array (
      '#' => 'settings for Zend Framework',
   ),

),

);
?>
========================================================



Smarty_ClipCache.class.php
function.include_clipcache.php
prefilter.clipcache.php
Code:
========================================================

all three, DL from here:

   http://www.phpinsider.com/smarty-forum/viewtopic.php?t=1343&start=23

and save in specified locations ...
========================================================


/path/to/httpd.conf
Code:
========================================================
<VirtualHost mydomain.com:80>
   ServerName     mydomain.com
   ServerAdmin    me@mydomain.com
   ServerRoot     /webapps/
   DocumentRoot   /webapps/document_root

   RewriteEngine off

   <Location / >
   
      RewriteEngine on
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule !\.(js|ico|gif|jpg|png|css)$ /index.php
   
      Options FollowSymLinks Includes ExecCGI MultiViews
      Order Deny,Allow
      Deny from all

# make sure you CHANGE THIS to allow your own network ...
      Allow from 10.0.0.6/255.255.255.248

   </Location>

LogLevel        debug
ErrorLog        /path/to/logs/mydomain.error.log
TransferLog     /path/to/logs/mydomain.access.log
CustomLog       /path/to/logs/mydomain.combo.log                 combined

RewriteLogLevel 9
RewriteLog      /path/to/logs/modrewrite.log

</VirtualHost>
========================================================




data.inc
Code:
========================================================
<?php
$smarty->assign('junk',
array(
      array('blah',
            array(array('blurg'
                       ),
                 )
           ),
      )
)
?>
========================================================


so, if you've installed all correctly, you'll be able to:

nav to http://mydomain.com
. --> you'll see loginpage.tpl

nav to http://mydomain.com/intro/welcome
. --> you'll see frontpage.tpl

nav to http://mydomain.com/(anything else)
. --> you'll redirect to http://mydomain.com, and thus see loginpage.tpl


Last edited by OpenMacNews on Sun May 07, 2006 9:29 pm; edited 8 times in total
Back to top
View user's profile Send private message
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Thu May 18, 2006 8:07 am    Post subject: Reply with quote

Hi OpenMacNews.

Nice job on this post! Amazingly, I got here from "This week in the Zend Framework. Issue #8". At anyrate, it seems you are being noticed Smile

Mainly I'm posting to mention that I'm now mainting the clipcache code at the wiki. There is an updated version there (0.1.7). http://smarty.incutio.com/?page=ClipCache

best regards
Back to top
View user's profile Send private message
OpenMacNews
Smarty Rookie


Joined: 03 Aug 2004
Posts: 34
Location: Floating on Io's Methane Seas ...

PostPosted: Fri May 19, 2006 9:24 pm    Post subject: Reply with quote

hi boots,

just fyi ... ZF's got a lot 'new' brewing under the hood.

new Zend_Config (replacing ezC, up-n-running 4 me already), Zend_Session (hopefully will help with gc, etc, haven't gotten to it yet) & Zend_Cache (which includes slot caching similar to {clipcache}). in addition, Zend_Cache's future will include shared_mm support -- i.e., Zend Optimizer & eAccelerator.

that said, i've decoupled from smarty for awhile ... just too much all at once. also worhwhile thinking abt what is best dealt with where, and avoiding redundancy.

there *is* a discussion @ ZF-list re: templating systems; Smarty among them ...

'default' position, not unexpectedly, is to use php itself for templating -- and in the future provide extensions to inlcude the likes of both PHPTAL and Smarty ...

cheers,

richard
Back to top
View user's profile Send private message
DimaCot
Smarty n00b


Joined: 12 Aug 2007
Posts: 1

PostPosted: Mon Aug 13, 2007 9:53 am    Post subject: Reply with quote

boots wrote:
Hi OpenMacNews.

Nice job on this post! Amazingly, I got here from "This week in the Zend Framework. Issue #8". At anyrate, it seems you are being noticed Smile

Mainly I'm posting to mention that I'm now mainting the clipcache code at the wiki. There is an updated version there (0.1.7).

best regards


Hi all! Can you tell me where i can download This week in the Zend Framework. Issue #8?

Thanks!
_________________
PHP forever!
Back to top
View user's profile Send private message
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Mon Aug 13, 2007 5:41 pm    Post subject: Reply with quote

From devzone.zend.com
Back to top
View user's profile Send private message
sayad
Smarty n00b


Joined: 28 Feb 2008
Posts: 4

PostPosted: Thu Feb 28, 2008 7:27 pm    Post subject: Reply with quote

DimaCot wrote:
boots wrote:
Hi OpenMacNews.

Nice job on this post! Amazingly, I got here from "This week in the Zend Framework. Issue #8". At anyrate, it seems you are being noticed Smile

Mainly I'm posting to mention that I'm now mainting the clipcache code at the wiki. There is an updated version there (0.1.7).

best regards


Hi all! Can you tell me where i can download This week in the Zend Framework. Issue #8?

Thanks!


yah.. i need help with that download location too..

thanks.
Back to top
View user's profile Send private message
sayad
Smarty n00b


Joined: 28 Feb 2008
Posts: 4

PostPosted: Thu Feb 28, 2008 7:28 pm    Post subject: Reply with quote

boots wrote:
From devzone.zend.com


any other location other then devzone.zend.com??
thanks.



--
Webkinz Recipes
Back to top
View user's profile Send private message
monotreme
Smarty Regular


Joined: 22 Feb 2004
Posts: 97
Location: USA

PostPosted: Mon Apr 21, 2008 7:04 pm    Post subject: awesome post Reply with quote

awesome post mate, too bad this forum doesn't have kudos, Id give it all to you today.
_________________
Your online 24/7 box office
http://www.tixrus.us
Back to top
View user's profile Send private message Visit poster's website
Canio
Smarty n00b


Joined: 01 May 2008
Posts: 1

PostPosted: Thu May 01, 2008 8:28 am    Post subject: Reply with quote

What about ZF 1.5? Does this method described here still work with the newest version? I mean it's two years old after all ...
Back to top
View user's profile Send private message
r-benTahir
Smarty n00b


Joined: 04 Mar 2011
Posts: 1

PostPosted: Fri Mar 04, 2011 12:43 pm    Post subject: God bless you Reply with quote

what a great effort.. i am such a big fan of smarty.. we have here our own framework..that is such a great thing in the world that it used the smarty's template engine.. hell i been trying to use it with zend.. i wish there be a framework that come with smarty as its template engine.. anyway u doing great..sure i will practice this handsome illustration. thanx alot for this. Smile
Back to top
View user's profile Send private message
Display posts from previous:   
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Frameworks All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP