Welcome, Guest. Register Now!
   
Mark Forums Read Mark Forums Read Mark Forums Read


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-27-2007, 05:04 AM
Junior Member
 
Join Date: Dec 2007
Posts: 9
Send a message via MSN to blurphp Send a message via Yahoo to blurphp
Default Smarty Implementation

Frist of all I am a newbie to zf. I have been out of the programming scene for a while.

I came across zf and decided to take a look at it.After reading the manual and some other sites I started playing around with it.

I guess first things first my directory structure
Code:
/application
    /config  --holds zf config file
    /controllers
    /models
    /Smarty  -- Smarty specific folders
         /cache
         /config
         /templates
         /templates_c
    /views
         /index
         /user
/library
    /Smarty  --  holds all smarty files
    /Zend  --  holds all zf files
.htaccess
index.php  --  bootstrapper file
I am using the zend veiw smarty layout that is in the manual. Zend Framework: Documentation

made a few adjustments to the Smarty.php script
PHP Code:
<?php
require_once 'Zend/View/Interface.php';
require_once 
'Smarty/Smarty.class.php';

class 
Zend_View_Smarty implements Zend_View_Interface
{
    
/**
     * Smarty object
     * @var Smarty
     */
    
protected $_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;
              //Changed this so the path is to the directoy where the folders are
              
$this->_smarty->template_dir $path.'/templates';
              
// Add the following so we can have all paths available to Smarty
              
$this->_smarty->compile_dir $path.'/templates_c';
              
$this->_smarty->cache_dir $path.'/cache';
              
$this->_smarty->config_dir $path.'/config';
              return;
          }
          throw new 
Exception('Invalid path provided');
      }
      
/**
       *  Retrieve the current template directory
       *
       *  @return string
       */
      
public function getScriptPaths()
      {
          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);
      }
      
/**
       *  Retrieve an assigned variable
       *
       *  @param string $key The variable name.
       *  @return mixed The variable value.
       */
      
public function __get($key)
      {
          return 
$this->_smarty->get_template_vars($key);
      }
      
/**
       *  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)
      {
          return 
$this->_smarty->fetch($name);
      }
}
My Bootstrapper looks like so:
PHP Code:
<?PHP

/*
*Error Reporting
*/
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors''On');
set_include_path(dirname(__FILE__) . '/library' PATH_SEPARATOR get_include_path());

/*
* Zend Loader
* Loads all the Zend classes the script uses
*/
require'Zend/loader.php';
/*
* Required Classes
* Class we need are accesssed through namespaces instead of direct files
* example Zend_Controller_Front will load /Zend/Controller/Front.php
*/
Zend_Loader::loadclass('Zend_Controller_Front');
Zend_Loader::loadclass('Zend_Config_Ini');
Zend_Loader::loadclass('Zend_Registry');
Zend_Loader::loadclass('Zend_Db');
Zend_Loader::loadclass('Zend_View_Smarty');

/*
* Load the config file
*/
$config = new Zend_Config_Ini('application/config/Config.ini''general');

/*
* Connect to database
*/
$db Zend_Db::factory($config->db);

/*
* Setup the controller
*/
$front Zend_Controller_Front::getInstance();
$front->setControllerDirectory('application/controllers');
$front->throwExceptions(true);

/*
* Run the page and display it  GO!!!
*/
$front->dispatch();
I saved the Smarty.php to Zend/View so I can load it using the Zend_Loader

My IndexController.php looks like
PHP Code:
<?PHP

class IndexController extends Zend_Controller_Action {

    function 
indexAction()
    {
        
//Logic Code goes here


        
$view = new Zend_View_Smarty();
        
$view->setScriptPath('application/Smarty');
        
$view->books 'Zend PHP 5 Certification Study Guide';
        
$view->author 'Davey Shafik and Ben Ramsey';
        
$rendered $view->render('bookinfo.tpl');


    }
}
What happens is everything works now to an extent but the .tpl files arenot outputing. I know I am overlooking something simple if someone could help me I would appreciate it.

If you need any more info just drop me a line.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 01-25-2008, 11:12 PM
Junior Member
 
Join Date: Jan 2008
Posts: 1
Default

Hello,

Perhaps you can try to expend Zend_View

Code:
class Zend_View_Smarty expends Zend_View implement...
Flo
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 02-25-2008, 07:19 AM
Junior Member
 
Join Date: Feb 2008
Posts: 1
Default

Thanks for this, I spent the whole day trying to get Smarty working with Zend. I just followed your directory structure and got it working.
You may have already figured out, but all I did to get it to render is to echo out what is rendered.

PHP Code:
$rendered $view->render('bookinfo.tpl'); 
echo 
$rendered
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 05-12-2008, 02:50 PM
Junior Member
 
Join Date: May 2008
Posts: 1
Default Error

I followed you method..but I'm getting an error..can u please find out what is the error
Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (index)' in D:\php\m4u2\framework\library\Zend\Controller\Disp atcher\Standard.php:249 Stack trace: #0 D:\php\m4u2\framework\library\Zend\Controller\Fron t.php(914): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #1 D:\php\m4u2\framework\index.php(48): Zend_Controller_Front->dispatch() #2 D:\php\m4u2\framework\public\index.php(2): include('D:\php\m4u2\fra...') #3 {main} thrown in D:\php\m4u2\framework\library\Zend\Controller\Disp atcher\Standard.php on line 249
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 05-12-2008, 10:42 PM
Junior Member
 
Join Date: Dec 2007
Posts: 9
Send a message via MSN to blurphp Send a message via Yahoo to blurphp
Default Info Needed

Can you send me the code that you used. I will be updating the code here soon made a few improvements that help alot of problems
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 05-12-2008, 11:54 PM
Junior Member
 
Join Date: Dec 2007
Posts: 9
Send a message via MSN to blurphp Send a message via Yahoo to blurphp
Default New changes and addons

I have updated the code to fix a few problems and make the view default to the Smarty Directory structure
Code:
/application
    /config  --holds zf config file
    /controllers -- Holds the Controllers needed for the script
          IndexController.php
          UserController.php
          AdminController.php
    /models
    /Smarty  -- Smarty specific folders
         /cache
         /config
         /templates  -- templates for the site are stored here
         /templates_c --smarty cached directory
    /modules
         Whatever modules you want for the script
/images
/js
/library
    /Smarty  --  holds all smarty files
    /Zend  --  holds all zf files
.htaccess
index.php  --  bootstrapper file
I am using the zend veiw smarty layout that is in the manual. Zend Framework: Documentation

made a few adjustments to the Smarty.php script (This stayed the Same)
PHP Code:
<?php 
require_once 'Zend/View/Interface.php'
require_once 
'Smarty/Smarty.class.php'

class 
Zend_View_Smarty implements Zend_View_Interface 

    
/** 
     * Smarty object 
     * @var Smarty 
     */ 
    
protected $_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; 
              //Changed this so the path is to the directoy where the folders are 
              
$this->_smarty->template_dir $path.'/templates'
              
// Add the following so we can have all paths available to Smarty 
              
$this->_smarty->compile_dir $path.'/templates_c'
              
$this->_smarty->cache_dir $path.'/cache'
              
$this->_smarty->config_dir $path.'/config'
              return; 
          } 
          throw new 
Exception('Invalid path provided'); 
      } 
      
/** 
       *  Retrieve the current template directory 
       * 
       *  @return string 
       */ 
      
public function getScriptPaths() 
      { 
          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); 
      } 
      
/** 
       *  Retrieve an assigned variable 
       * 
       *  @param string $key The variable name. 
       *  @return mixed The variable value. 
       */ 
      
public function __get($key
      { 
          return 
$this->_smarty->get_template_vars($key); 
      } 
      
/** 
       *  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
      { 
          return 
$this->_smarty->fetch($name); 
      } 
}
Bootstrapper is like so:
PHP Code:
<?PHP

/**
*  Set up time zone.
*/
date_default_timezone_set('America/Chicago');

/**
* Error Reporting
*/
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors''On');

/**
 * Set the include paths up
 */
set_include_path(dirname(__FILE__) . '/library'PATH_SEPARATOR .
        
'./application/models/' PATH_SEPARATOR get_include_path());

/**
* Zend Loader
* Loads all the Zend classes the script uses
* Register an autoload() callback.  This is optional but very handy.
*/
require 'Zend/loader.php';
Zend_Loader::registerAutoload();

/**
 * Start Zend Session
 * Load the session values from config
 */
$sconfig = new Zend_Config_Ini('application/config/Config.ini''sessions');
Zend_Session::setOptions($sconfig->toArray());
Zend_Session::start();
/*
* Load the config file and set it to the Registry
*/
$config = new Zend_Config_Ini('application/config/Config.ini''general');
$dbadapter $config->db->adaptor;
Zend_Registry::set('dbadapter'$dbadapter);

/*
* Connect to database
*/
$db Zend_Db::factory($config->db->adapter$config->db->params->toArray());
Zend_Registry::set('db'$db);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
Zend_Registry::set('db'$db);


$front Zend_Controller_Front::getInstance();
/**
  *  Set up routes the script will use
  * 
*/
$router $front->getRouter();
$rconfig = new Zend_Config_Ini('application/config/routes.ini''routes');
$router->addConfig($rconfig'routes');
$front->setRouter($router);
$front->setControllerDirectory(array(
'default' => 'application/controllers',
'blog' => 'modules/blog/controllers',
'news' => 'modules/news/controllers',
'chat' => 'modules/chat/controllers',
'forum' => 'modules/forum/controllers',
'calender' => 'modules/calander/controllers',
'cart' => 'modules/cart/controllers',
'games' => 'modules/games/controllers'
));


//$front->setBaseUrl('/projects/myapp'); // set the base url!
$front->throwExceptions(true);
$front->setParam('useDefaultControllerAlways'true);

/*
* Run the page and display it  GO!!!
*/
$front->dispatch();
The controller files have this basic set up
PHP Code:
class IndexController extends Zend_Controller_Action {

    public function 
init()
    {
        
// Set Smarty defaults so it is availale throught the class
        
$this->view = new Zend_View_Smarty();
        
$this->view->setScriptPath('application/Smarty');
        
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($this->view);
        
$viewRenderer->setViewBasePathSpec('application/Smarty/templates');
        
$viewRenderer->setViewScriptPathSpec(':module/:controller/:action.:suffix');
        
$viewRenderer->setViewScriptPathNoControllerSpec(':action.:suffix');
        
$viewRenderer->setViewSuffix('tpl');
        
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
        require 
'application/config/site_setting.php';
        
$settings $configarray;
        
$this->view->assign('set'$settings);

    }

    public function 
indexAction()
    {
        
//Logic Code goes here
        
$results = array(
        
'author' => 'Davey Shafik and Ben Ramsey',
        
'title' => 'Zend PHP 5 Certification Study Guide'
        
);


        
$this->view->assign('results'$results);
        
$this->view->display('book_view.tpl');
    }

Routes file sample: We use this for a sort referrer url that defaults to admin if the user is not found and redirects to the main page automatically which was really neat
PHP Code:
[routes]
routes.r.type "Zend_Controller_Router_Route"
routes.r.route "r/:username"
routes.r.defaults.controller user
routes
.r.defaults.action setreferrer
routes
.r.default.username admin 
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 05-12-2008, 11:55 PM
Junior Member
 
Join Date: Dec 2007
Posts: 9
Send a message via MSN to blurphp Send a message via Yahoo to blurphp
Default Continued

Changes are simple but made a lot more flexiblity in the script and in what we where trying to accomplish the use of the routes helped make the url short and sweet and search engine friendly.

It also Bypasses the views directory and goes straight to the smarty directory where all templates are stored. So we don't need to echo the rendered object it is displayed automatically when everything is done right.

I hope this helps anyone that likes the flexibility of smarty if you find a better way of doing this and want to share drop me a line.

Last edited by blurphp : 05-12-2008 at 11:57 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote