Mediovski Technology

Smarty 3.0 RC3 + Zend Framework 1.10.4

Data: 8 August 2010 3:40 PM Autor: Michał Szkodziński | Kategoria: PHP,Programowanie,Smarty,Zend Framework

Opis uruchomienia Smarty 3.0 we współpracy z Zend Framework oraz przykłady użycia helperów.

Przygotowany na podstawie aplikacji działającej z:

  • Apache 2.2.11
  • PHP 5.3.1
  • MySQL 5.1.32
  • Zend Framework 1.10.4
  • Smarty 3.0 RC3

Więcej na temat Smarty 3 można przeczytać tutaj.

Smarty 3.0 RC3 można pobrać z:

Część struktury aplikacji (* oznaczono pliki, których kod źródłowy jest przedstawiony w dalszej części wpisu):

structure

Widok inicjalizujemy w Bootstrapie w metodzie _initView() (Bootstrap.php):

class Bootstrap
{
 
	(...)
 
	/**
	* Inicjalizacja widoku
	*/
	protected function _initView()
	{
		// Połączenie Zend View - Smarty
		$view = new My_View_Smarty(array(
			'scriptPath' => 'application/',
			'params' => array(
				'plugins_dir' => 'plugins',
				'compile_dir' => 'tmp/templates_c'
			),
			'helperDirs' => array(
				'My/View/Helper' => 'My_View_Helper_',
				'Zend/View/Helper' => 'Zend_View_Helper_'
			)
		));
 
		// View Renderer
		Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')
		->setViewScriptPathSpec(':module/view/:controller/:action.:suffix')
		->setViewSuffix('tpl')
		->setView($view);
 
		// Zend Layout
		$view->layout = Zend_Layout::startMvc(array(
			'inflectorTarget' => 'layout/:script.:suffix',
			'layout' => 'default',
			'viewSuffix' => 'tpl'
		))->setView($view);
	}
 
	(...)
 
}

Rozszerzamy klasę Zend_View_Abstract o obsługę Smarty. Klasa wygląda bardzo podobnie do klas używanych podczas łączenia Smarty 2 z ZF (library/My/View/Smarty.php).

class My_View_Smarty extends Zend_View_Abstract
{
	/**
	* Obiekt Smarty
	*
	* @var My_Smarty
	*/
	protected $_smarty = null;
 
	/**
	* Konstruktor
	*
	* @param array $config dane konfiguracyjne
	*/
	public function __construct($config = array())
	{
		$this->_smarty = new My_Smarty();
		$this->_smarty->setZendView($this);
 
		foreach ($config['params'] as $key => $value) {
			$this->_smarty->$key = $value;
		}
 
		$this->setScriptPath($config['scriptPath']);
 
		// Ścieżki do helperów
		foreach ($config['helperDirs'] as $path => $prefix) {
			$this->addHelperPath($path, $prefix);
		}
	}
 
	/**
	 * Zwraca obiekt Smarty
	 *
	 * @return My_Smarty
	 */
	public function getEngine()
	{
		return $this->_smarty;
	}
 
	/**
	* Ustawia ścieżkę do szablonów
	*
	* @param string $path ścieżka
	*/
	public function setScriptPath($path)
	{
		if (null === $path) {
			return;
		}
 
		$this->_smarty->template_dir = $path;
	}
 
	/**
	* Pobiera ścieżki do szablonów
	*
	* @return array tablica ścieżek
	*/
	public function getScriptPaths() {
		return array($this->getScriptPath(null));
	}
 
	/**
	* Zwraca ściezkę do plików tpl
	*
	* @return string ścieżka
	*/
	public function getScriptPath($name) {
		return $this->_smarty->template_dir;
	}
 
	/**
	* Ustawienie parametru
	*
	* @param string $key klucz
	* @param mixed $value wartość
	*/
	public function setParam($key, $value)
	{
		$this->_smarty->$key = $value;
	}
 
	/**
	* Ustawia zmienną w widoku
	*
	* @param string $key nazwa zmiennej
	* @param mixed $value wartość zmiennej
	*/
	public function __set($key, $value)
	{
		$this->_smarty->assign($key, $value);
	}
 
	/**
	* Pobiera zmienną z widoku
	*
	* @param string $key nazwa zmiennej
	* @return mixed wartość zmiennej
	*/
	public function __get($key)
	{
		return $this->_smarty->getTemplateVars($key);
	}
 
	/**
	* Sprawdzenie czy zmienna jest ustawiona w widoku
	*
	* @param string $key nazwa zmiennej
	* @return boolean czy zmienna jest ustawiona
	*/
	public function __isset($key)
	{
		return null === $this->_smarty->getTemplateVars($key);
	}
 
	/**
	* Usunięcie zmiennej z widoku
	*
	* @param string $key nazwa zmiennej
	*/
	public function __unset($key)
	{
		$this->_smarty->clearAssign($key);
	}
 
	/**
	* Przypisywanie zmiennych do widoku
	*
	* @param string|array $var nazwa zmiennej lucz tablica par (klucz => wartość)
	* @param mixed $value wartość zmiennej
	*/
	public function assign($var, $value = null)
	{
		if (is_array($var)) {
			$this->_smarty->assign($var);
			return;
		}
 
		$this->_smarty->assign($var, $value);
	}
 
	/**
	* Usunięcie wszystkich przypisanych do widoku zmiennych
	*/
	public function clearVars()
	{
		$this->_smarty->clearAllAssign();
	}
 
	/**
	* Renderowanie szablonu
	*
	* @param string $name nazwa szablonu
	* @return string wyrenderowany szablon
	*/
	public function render($name)
	{
		if (file_exists($this->getScriptPath($name) . $name)) {
			return $this->_smarty->fetch($name);
		}
		return null;
	}
 
	/**
	* Rozszerzenie abstrakcyjnej metody klasy nadrzędnej
	*/
	protected function _run()
	{
	}
}

Rozszerzamy klasę Smarty o obsługę helperów widoku Zend Framework (library/My/Smarty.php):

class My_Smarty extends Smarty
{
	/**
	* Obiekt widoku
	*
	* @var Zend_View_Abstract
	*/
	protected $_zendView = null;
 
	/**
	* resource type used if none given
	*
	* @var string
	*/
	public $default_resource_type = 'my'; 
 
	/**
	* Ustawienie widoku
	*
	* @param Zend_View_Abstract $view obiekt widoku
	*/
	public function setZendView(Zend_View_Abstract $view)
	{
		$this->_zendView = $view;
	}
 
	/**
	* Pobranie widoku
	*
	* @param Zend_View_Abstract obiekt widoku
	*/
	public function getZendView()
	{
		return $this->_zendView;
	}
 
	/**
	 * fetches a rendered Smarty template
	 *
	 * @param string $template the resource handle of the template file or template object
	 * @param mixed $cache_id cache id to be used with this template
	 * @param mixed $compile_id compile id to be used with this template
	 * @param object $ |null $parent next higher level of Smarty variables
	 * @return string rendered template output
	 */
	public function fetch($template, $cache_id = null, $compile_id = null, $parent = null, $display = false)
	{
		return parent::fetch($this->default_resource_type . ':' . $template, $cache_id, $compile_id, $parent, $display);
	}
}

Plugin Smarty do obsługi nowego typu zasobów (library/Smarty/plugins/resource.my.php):

class Smarty_Resource_My extends Smarty_Internal_Resource_File {
    public $compiler_class = 'Smarty_Compiler_My';
}

Kompilator nowego typu zasobów (library/Smarty/plugins/compiler.my.php):

<?php class Smarty_Compiler_My extends Smarty_Internal_SmartyTemplateCompiler {
 
	public function callTagCompiler($tag, $args, $param1 = null, $param2 = null, $param3 = null)
	{
		if ($r = parent::callTagCompiler($tag, $args, $param1, $param2, $param3)) {
			return $r;
		}
 
		if (isset($args['_method'])) {
			$method = $args['_method'];
			unset($args['_method']);
		} else {
			$method = '\'' . $tag . '\'';
		}
 
		return '<?php echo call_user_func_array(array($_smarty_tpl->smarty->getZendView()
			->getHelper(\'' . $tag . '\'), ' . $method . '), array(' . implode(',', $args) . ')); ?>';
	}
}

Przykłady użycia helperów ZF w szablonach, aby wywołać inną metodę niż domyślną należy jej nazwę podać jako wartość parametru _method.

{baseUrl}
{url urlOptions=['module' => 'Default', 'controller' => 'index', 'action' => 'index'] name='default' reset=true}
{myHelper _method='myMethod' options=['key1' => 'value1', 'key2' => 'value2'] limit=20}

1 Comment »

  1. Comment by marcoman — 14 August 2010 @ 4:30 AM

    Hello, thank you for this guide. I tried it and it works just fine. One problem though is that the zend helpers aren’t recognized on child templates. Could you please address that issue?

RSS feed for comments on this post. TrackBack URL

Leave a comment


five + 6 =

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
RSS