integrazione con smarty

<?php

Ciao Gianni,

sto cercando di utilizzare smarty al posto di Zend_View, per fare ci ho creato una libreria in libs :

/Libs
  /Zend
  /Smarty
    Smarty.class.php
    Smarty_compiler.class.php
    debug.tpl
    Config_file.class.php
    /internals
    /plugins
/Mialibreria
  /View
    Smarty.php
  /Controller
    Base.php

Mialibreria_View_Smarty contenuta in Smarty.php

non altro che Zend_View_Interface implementato sui metodi di smarty.

I file di smarty (Smarty/Smarty.class.php) vengono inclusi qui dentro.

il codice questo :

<?php

include DIR_LIBS . 'Smarty/Smarty.class.php';

class Mialibreria_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;
      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);
  }
}

Mialibreria_Controller_Base la classe che utilizzo per la scrittura dei controller, questa estende Zend_Controller_Action

questa contiene metodi comuni a tutti i controller ed in pi

<?php
class Mialibreria_Controller_Base extends Zend_Controller_Action 
{   
  public function initView()
  {
    if (null === $this->view) {
      if (Zend_Registry::isRegistered('view')) {
        $this->view = Zend_Registry::get('view');
      } else {
        $this->view = new Mialibreria_View_smarty();
        $this->view->setBasePath('var/templates/');
      }
    }

    return $this->view;
  }
  
  public function init()
  {
    $this->_helper->removeHelper('viewRenderer');
  }
}

Se nel file di bootstrap

  // ... ... ... 
  $frontController = Zend_Controller_Front::getInstance();
  $frontController->setControllerDirectory(DIR_CONTROLLERS)
          //->setParam('noViewRenderer', true)
          ->dispatch(); 
  // ... ... ...

rimuovo il commento a setparam ottengo una bella pagina bianca.

quando invece commento ottendo la mia pagina di errore gestita con :

<?php

require_once 'Zend/Controller/Action.php';

class ErrorController extends Mialibreria_Controller_Base
{
  public function errorAction()
  {
    $errors = $this->_getParam('error_handler');
    switch ($errors->type) {
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
        $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');
        $errorMessage = '404 Error Page Not found';
        break;
        
      default:
        $logConfig = Zend_Registry::get('logConfig');
        $errorType = 'Application Error';
        $errorMessage = 'The system has reported an unknown error. A log file has been created for the event.';
        include DIR_VAR . '/errors/startupError.html';
        
        $exception = $errors->exception;
        $writer = new Zend_Log_Writer_Stream($logConfig->saveDir . $logConfig->emergFile, 'wb');
        
        $formatter = new Zend_Log_Formatter_Simple('%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL);
        $log = new Zend_Log($writer);
        $log->log($exception->getMessage() . "\n" . print_r($exception->getTraceAsString(),true), Zend_Log::EMERG);
        break;
    }
  }
}

il log dice :

2007-10-21T16:01:50+02:00 EMERG (0): script 'catalog/view.phtml' not found in path (C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\Mialibreria\app\default\views\scripts\)
#0 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\View\Abstract.php(765): Zend_View_Abstract->_script('catalog/view.ph...')
#1 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Action\Helper\ViewRenderer.php(742): Zend_View_Abstract->render('catalog/view.ph...')
#2 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Action\Helper\ViewRenderer.php(763): Zend_Controller_Action_Helper_ViewRenderer->renderScript('catalog/view.ph...', NULL)
#3 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Action\Helper\ViewRenderer.php(811): Zend_Controller_Action_Helper_ViewRenderer->render()
#4 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Action\HelperBroker.php(160): Zend_Controller_Action_Helper_ViewRenderer->postDispatch()
#5 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Action.php(504): Zend_Controller_Action_HelperBroker->notifyPostDispatch()
#6 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Dispatcher\Standard.php(238): Zend_Controller_Action->dispatch('viewAction')
#7 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\libs\Zend\Controller\Front.php(920): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#8 C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\sito\index.php(76): Zend_Controller_Front->dispatch()
#9 {main}

Ho cercato di spiegare tutto nei minimi dettagli, spero che possa aiutarmi :D

:bye:

inviato 9 anni fa
Andrea Turso
Andrea Turso
86
modificato 9 anni fa
X 0 X

Hai dato un'occhiata a questo articolo?

http://devzone.zend.com/node/view/id/120

risposto 9 anni fa
Gianni Tomasicchio
X 0 X

In effetti non che mi piaccia molto com' stato integrato.

Comunque ho risolto.

Dai uno sguardo, possibili miglioramenti?

<?php 
//controller BASE ( tutti i actionController estendono questa base ) 
class Solemare_Controller_Base extends Zend_Controller_Action 
{  
  protected $_db; 
  
  public function initView()
  {
    $config = Zend_Registry::get('tplConfig');
    if (null === $this->view) {
      if (Zend_Registry::isRegistered('view')) {
        $this->view = Zend_Registry::get('view');
      } else {
        $tplDirs = array('compile_dir'   => $config->compileDir,
                  'config_dir'  => $config->configDir,
                  'cache_dir'  => $config->cacheDir,
                  'caching'   => $config->caching,
                  'cache_lifetime'=> $config->cacheLifetime);                  
        $this->view = new Solemare_View_smarty($config->templateDir, $tplDirs);
        Zend_Registry::set('view', $view);        
      }
    }

    return $this->view;
  }
  
  public function init()
  {
    $this->_db = Zend_Registry::get('db');
    $this->_helper->removeHelper('viewRenderer');
    $this->initView();
  }
}

//esempio di estensione di questo controller
class IndexController extends Solemare_Controller_Base
{
  public function indexAction()
  {    
    $this->view->assign('title', 'bar');
    $this->view->assign('foo', true);
    $this->view->assign('bar', 'asdasdasdasd');
    $this->view->render('index.tpl');

  }
}

A deduzione, avrei giurato che initView fosse eseguito automaticamente, ma a quanto pare mi sbagliavo!

:bye:

risposto 9 anni fa
Andrea Turso
Andrea Turso
86
X 0 X
Effettua l'accesso o registrati per rispondere a questa domanda