Extending a class which has static methods - php

I want to extend KOHANA's i18n class in a module so that I can lookup a DB first to look for translations before it looks up the default file structure. The problem is that the method I want to override is static.
The original class has a method get() so I call my class: Appointedd_I18n::get('Term goes here...') and that method calls load(). That is the method I want to override but because it's static it's not loading MY method it's loading the original one.
Here's my module/class:
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Extends the Kohana translation code to include a db lookup.
*
*/
class Appointedd_I18n extends Kohana_I18n {
/**
* Returns the translation table for a given language.
*
* // Get all defined Spanish messages
* $messages = I18n::load('es-es');
*
* #param string $lang language to load
* #return array
*/
public static function load($lang)
{
die('think I\'ll look up the db'); // to test this method is being called
if (isset(I18n::$_cache[$lang]))
{
return I18n::$_cache[$lang];
}
// New translation table
$table = array();
// Split the language: language, region, locale, etc
$parts = explode('-', $lang);
do
{
// Create a path for this set of parts
$path = implode(DIRECTORY_SEPARATOR, $parts);
if ($files = Kohana::find_file('i18n', $path, NULL, TRUE))
{
$t = array();
foreach ($files as $file)
{
// Merge the language strings into the sub table
$t = array_merge($t, Kohana::load($file));
}
// Append the sub table, preventing less specific language
// files from overloading more specific files
$table += $t;
}
// Remove the last part
array_pop($parts);
}
while ($parts);
// Cache the translation table locally
return I18n::$_cache[$lang] = $table;
}
} // END class Appointedd_i18n
Here is the KOHANA_I18n class:
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Internationalization (i18n) class. Provides language loading and translation
* methods without dependencies on [gettext](http://php.net/gettext).
*
* Typically this class would never be used directly, but used via the __()
* function, which loads the message and replaces parameters:
*
* // Display a translated message
* echo __('Hello, world');
*
* // With parameter replacement
* echo __('Hello, :user', array(':user' => $username));
*
* #package Kohana
* #category Base
* #author Kohana Team
* #copyright (c) 2008-2012 Kohana Team
* #license http://kohanaframework.org/license
*/
class Kohana_I18n {
/**
* #var string target language: en-us, es-es, zh-cn, etc
*/
public static $lang = 'en-us';
/**
* #var string source language: en-us, es-es, zh-cn, etc
*/
public static $source = 'en-us';
/**
* #var array cache of loaded languages
*/
protected static $_cache = array();
/**
* Get and set the target language.
*
* // Get the current language
* $lang = I18n::lang();
*
* // Change the current language to Spanish
* I18n::lang('es-es');
*
* #param string $lang new language setting
* #return string
* #since 3.0.2
*/
public static function lang($lang = NULL)
{
if ($lang)
{
// Normalize the language
I18n::$lang = strtolower(str_replace(array(' ', '_'), '-', $lang));
}
return I18n::$lang;
}
/**
* Returns translation of a string. If no translation exists, the original
* string will be returned. No parameters are replaced.
*
* $hello = I18n::get('Hello friends, my name is :name');
*
* #param string $string text to translate
* #param string $lang target language
* #return string
*/
public static function get($string, $lang = NULL)
{
if ( ! $lang)
{
// Use the global target language
$lang = I18n::$lang;
}
// Load the translation table for this language
$table = I18n::load($lang);
// Return the translated string if it exists
return isset($table[$string]) ? $table[$string] : $string;
}
/**
* Returns the translation table for a given language.
*
* // Get all defined Spanish messages
* $messages = I18n::load('es-es');
*
* #param string $lang language to load
* #return array
*/
public static function load($lang)
{
if (isset(I18n::$_cache[$lang]))
{
return I18n::$_cache[$lang];
}
// New translation table
$table = array();
// Split the language: language, region, locale, etc
$parts = explode('-', $lang);
do
{
// Create a path for this set of parts
$path = implode(DIRECTORY_SEPARATOR, $parts);
if ($files = Kohana::find_file('i18n', $path, NULL, TRUE))
{
$t = array();
foreach ($files as $file)
{
// Merge the language strings into the sub table
$t = array_merge($t, Kohana::load($file));
}
// Append the sub table, preventing less specific language
// files from overloading more specific files
$table += $t;
}
// Remove the last part
array_pop($parts);
}
while ($parts);
// Cache the translation table locally
return I18n::$_cache[$lang] = $table;
}
} // End I18n
if ( ! function_exists('__'))
{
/**
* Kohana translation/internationalization function. The PHP function
* [strtr](http://php.net/strtr) is used for replacing parameters.
*
* __('Welcome back, :user', array(':user' => $username));
*
* [!!] The target language is defined by [I18n::$lang].
*
* #uses I18n::get
* #param string $string text to translate
* #param array $values values to replace in the translated text
* #param string $lang source language
* #return string
*/
function __($string, array $values = NULL, $lang = 'en-us')
{
if ($lang !== I18n::$lang)
{
// The message and target languages are different
// Get the translation for this message
$string = I18n::get($string);
}
return empty($values) ? $string : strtr($string, $values);
}
}
Is there a way I extend Kohana_I18n to include a db update without editing the system class?

"Is there a way I extend Kohana_I18n to include a db update without editing the system class?"
Yes.
It sounds like you are either unfamiliar with Kohana's Cascading File System, you don't understand how it could be useful in this circumstance or that you don't want to change I18n's behavior for whatever reason.
If the last is not the case then just rename Appointedd_I18n to I18n and change the filename accordingly. SYSPATH/classes/I18n.php a file that just contains class I18n extends Kohana_I18n {}. And if you look at SYSPATH/classes/Kohana/I18n.php you will see self or Kohana_I18n is never used to call anything.
They have consistently used I18n in the Kohana_I18n class so that you can 'replace' the I18n class and change its behavior.

Since Kohana_I18n::get() calls I18n::load(), all you have to do is override the Kohana_I18n::get() method so that it calls the Appointedd_I18n::load() method.
class Appointedd_I18n extends Kohana_I18n {
...
public static function get($string, $lang = NULL)
{
if ( ! $lang)
{
// Use the global target language
$lang = I18n::$lang;
}
// Load the translation table for this language
$table = self::load($lang);
// Return the translated string if it exists
return isset($table[$string]) ? $table[$string] : $string;
}
...
}

Related

ezplatform extracting the uri of an image for the current language of the current site access

Is there a best practice to extract the uri of an image in the current translation of the current site access in twig?
We have an object with a translatable image field. Rendering the image with the helper: ez_render_field works fine.
But I now need to also extract the uri of the image for the current siteaccess but cannot find a way of doing this.
Trying to use the ez_field just results in
{{ ez_field(content, "image_1").uri }}
An exception has been thrown during the rendering of a template
("Catchable Fatal Error: Object of class
eZ\Publish\API\Repository\Values\Content\Field could not be converted
to string").
The content object looks like:
here is the standard way to achieve this.
where image is the field's name and teaser is the image variante you defined. by default you have original , small , large and ....
{% set imgAlias = ez_image_alias( content.getField( "image" ), content.versionInfo, 'teaser' ) %}
{{ dump(imgAlias.url) }}
( imgAlias.url is what you are looking for. )
here is the link to Documentation: https://doc.ez.no/display/DEVELOPER/ez_image_alias
I don't know if this is the best method, but this is what i came up with:
{{ getImageUri( content.fields.image, ezpublish.siteaccess ) }}
The custom twig functions
use Symfony\Component\Yaml\Yaml;
/**
* Class AppExtension
*
* #package AppBundle\Twig
*/
class AppExtension extends \Twig_Extension
{
public function getFilters()
{
return [
];
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('getYml', [$this, 'getYml']),
new \Twig_SimpleFunction('getImageUri', [$this, 'getImageUri']),
];
}
/**
* Pass an image object and return the original image uri in the current site access
*
* #param $imageField
* #param $siteAccess
*
* #return mixed
*/
public function getImageUri( $imageField, $siteAccess ){
$languages = $this->getYml('ezplatform', 'ezpublish:system:'.$siteAccess->name.':languages');
if($languages){
foreach($languages as $language){
if( array_key_exists( $language, $imageField ) ){
return $imageField[$language]->uri;
}
}
}
return $imageField[array_keys($imageField)[0]]->uri;
}
/**
* Internal cache of the yml files already fetched
*
* #var array
*/
private $yamlCache = [];
/**
* Return content from a app/config/*.yml file. Pass in a : separated path to fetch what you need. Empty returns the whole yml as an array
*
* #param $fileMinusExt
* #param bool $path
* #param string $delimiter
*
* #return bool|mixed
*/
public function getYml($fileMinusExt, $path = false, $delimiter = ':')
{
if (in_array($fileMinusExt, $this->yamlCache)) {
$value = $this->yamlCache[$fileMinusExt];
} else {
$value = Yaml::parse(file_get_contents('../app/config/' . $fileMinusExt . '.yml'));
}
if ($path === false) {
return $value;
}
return $this->_getYmlPath($value, explode($delimiter, $path));
}
/**
* Extract value from array
*
* #param $values
* #param $parts
*
* #return bool
*/
private function _getYmlPath($values, $parts)
{
try {
$subVal = $values[array_shift($parts)];
if (count($parts) > 0) {
return $this->_getYmlPath($subVal, $parts);
}
return $subVal;
} catch (\Exception $e) {
return false;
}
}
}

PHP in Template Class

I am currently working on a template class from broculus.
Now I wanted to install PHP into the template using the class. Unfortunately, I am currently failing.
By eval it is certainly not I have established. Now I wanted to ask if you have an idea how I can solve the problem easily.
Link: http://www.broculos.net/2008/03/how-to-make-simple-html-template-engine.html#.WS8jfWjyjIX
In that code I want to get the value of a variable, which is php code.
That code shall be executed.
Example:
$row_1->content = '$name = 'Pagetitle'; echo $name;';
$row->content contains php and complete scripts.
$layout = new Template("template/layout.tpl");
$layout->set("title", $sitename);
$layout->set("content", eval($row_1->content));
Class:
/**
* Simple template engine class (use [#tag] tags in your templates).
*
* #link http://www.broculos.net/ Broculos.net Programming Tutorials
* #author Nuno Freitas <nunofreitas#gmail.com>
* #version 1.0
*/
class Template {
/**
* The filename of the template to load.
*
* #access protected
* #var string
*/
protected $file;
/**
* An array of values for replacing each tag on the template (the key for each value is its corresponding tag).
*
* #access protected
* #var array
*/
protected $values = array();
/**
* Creates a new Template object and sets its associated file.
*
* #param string $file the filename of the template to load
*/
public function __construct($file) {
$this->file = $file;
}
/**
* Sets a value for replacing a specific tag.
*
* #param string $key the name of the tag to replace
* #param string $value the value to replace
*/
public function set($key, $value) {
$this->values[$key] = $value;
}
/**
* Outputs the content of the template, replacing the keys for its respective values.
*
* #return string
*/
public function output() {
/**
* Tries to verify if the file exists.
* If it doesn't return with an error message.
* Anything else loads the file contents and loops through the array replacing every key for its value.
*/
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
/**
* Merges the content from an array of templates and separates it with $separator.
*
* #param array $templates an array of Template objects to merge
* #param string $separator the string that is used between each Template object
* #return string
*/
static public function merge($templates, $separator = "\n") {
/**
* Loops through the array concatenating the outputs from each template, separating with $separator.
* If a type different from Template is found we provide an error message.
*/
$output = "";
foreach ($templates as $template) {
$content = (get_class($template) !== "Template")
? "Error, incorrect type - expected Template."
: $template->output();
$output .= $content . $separator;
}
return $output;
}
}
I found a solution using ob_start. In the panel.php I execute the PHP code via eval.
// Ausgabepuffer an
ob_start();
// Skript ausführen
$_GET['panel'] = 1;
include('panel.php');
// Ausgabe aus Puffer holen
$inhalt = ob_get_contents();
// Puffer schließen
ob_end_clean();
//Layout holen
$layout = new Template("template/layout.tpl");
$layout->set("title", $sitename);
$layout->set("content", $inhalt);
What do you think about this?
Es war keine wirkliche Lösung, wie es sich herausgestellt hat.
Versuche nun die Template Engine von Smarty zu nutzen. Weiß jemand wie ich dort PHP im Template darstellen kann?
require '../libs/Smarty.class.php';
$smarty = new Smarty;
$smarty->compile_check = true;
$smarty->debugging = false;
$smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill");
$smarty->assign("Menu","MENU");
$smarty->assign("Content", "echo 'Testinhalt soll angezeigt werden.'; ");
$smarty->display('index.tpl');

Symofny2 Get a listing of available Logical Controller Names

I need to show a choice with a list of all available controllers as Logical Controller Names AcmeBundle:ControllerName:ActionName
I see that CLI command php app/console router:debug dumps a similar listing, but with controller names, e.g. fos_user_security_login.
How can I ask Symfony for their Logical Controller Name representation?
Thanks!
As #hous said, this post was useful, but incomplete and its accepted answer misleading.
A) Getting the controllers
With this code I get all controllers, but with their FQCN::method or service:method notation.
// in a Controller.
$this->container->get('router')->getRouteCollection()->all()
Some Background
The previous method will return a big array of routes. Follows one key => value:
'admin_chacra' => // route name
object(Symfony\Component\Routing\Route)[1313]
...
private 'defaults' =>
array (size=1)
'_controller' => string 'Application\ColonizacionBundle\Controller\ChacraController::indexAction' (length=71)
The FQCN::method notation is the right argument to the build method of ControllerNameParser::build(). The service notation is not parsed, as it gets handled by the following code in ControllerResolver::createController()`
$count = substr_count($controller, ':');
if (2 == $count) {
// controller in the a:b:c notation then
/* #var $this->parser ControllerNameParser parse() is the oposite of build()*/
$controller = $this->parser->parse($controller);
} elseif (1 == $count) {
// controller in the service:method notation
list($service, $method) = explode(':', $controller, 2);
return array($this->container->get($service), $method);
} else {
throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
}
B) Generating Logical Controller Names
So all I have to do is filter out the controllers I don't want, {FOS; framework's; etc} and feed build() with each selected one. E.g. by selecting only the _controller attributes that matches my bundles namespace Application\*Bundle in my case.
Here's the build docBlock
/**
* Converts a class::method notation to a short one (a:b:c).
*
* #param string $controller A string in the class::method notation
*
* #return string A short notation controller (a:b:c)
*
* #throws \InvalidArgumentException when the controller is not valid or cannot be found in any bundle
*/
My Implementation
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
class ActivityRoleControllerType extends AbstractType
{
...
/**
* Controller choices
*
* #var array
*/
private static $controllers = array();
/**
* Controller Name Parser
*
* #var ControllerNameParser
*/
private $parser;
/**
* expects the service_container service
*/
public function __construct(ContainerInterface $container)
{
$this->parser = new ControllerNameParser($container->get('kernel'));
self::$controllers = $this->getControllerLogicalNames(
$container->get('router')->getRouteCollection()->all(), $this->parser
);
}
/**
* Creates Logical Controller Names for all controllers under \Application\*
* namespace.
*
* #param Route[] $routes The routes to iterate through.
* #param ControllerNameParser $parser The Controller Name parser.
*
* #return array the ChoiceType choices compatible array of Logical Controller Names.
*/
public function getControllerLogicalNames(array $routes, ControllerNameParser $parser)
{
if (! empty(self::$controllers)) {
return self::$controllers;
}
$controllers = array();
/* #var $route \Symfony\Component\Routing\Route */
foreach ($routes as $route) {
$controller = $route->getDefault('_controller')
if (0 === strpos($controller, 'Application\\')) {
try {
$logicalName = $parser->build($controller);
$controllers[$logicalName] = $logicalName;
} catch (\InvalidArgumentException $exc) {
// Do nothing, invalid names skiped
continue;
}
}
}
asort($controllers);
return $controllers;
}
}

Zend and Smarty 3 integration using

I am trying to change the layout content in my controller, which only seems to overwrite it, only append.
I have built a CMS using Zend and Smarty. I have one main layout with, which displays the content for each page:
{$this->layout()->content}
Although when I try to overwrite the 'content' in the controller with a new content area this causes both the index/index.tpl and contact/contact.tpl to be displayed:
$this->view->content = $this->view->display('contact/contact.tpl');
I know I could manually assign the content to a view smarty variable, although I would like to reduce the assigns in smarty and use Zend.
In my application.ini
smarty.caching = 1
smarty.cache_lifetime = 14400
smarty.template_dir = PATH "/templates/default/"
smarty.compile_dir = PATH "/tmp/smarty_compile/"
smarty.plugins_dir = APPLICATION_PATH "/plugins/smarty/"
smarty.config_dir = ""
smarty.cache_dir = PATH "/tmp/smarty_cache/"
smarty.left_delimiter = "{"
smarty.right_delimiter = "}"
In my bootstrap.php
protected function _initView()
{
$view = new Web_View_Smarty($this->getOption('smarty'));
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setViewSuffix('tpl');
$viewRenderer->setView($view);
$this->bootstrap('layout');
$layout = Zend_Layout::getMvcInstance();
$layout->setViewSuffix('tpl');
return $view;
}
In my Smarty.php
<?php
/**
* Smarty template engine integration into Zend Framework
*/
class Web_View_Smarty extends Zend_View_Abstract
{
/**
* Instance of Smarty
* #var Smarty
*/
protected $_smarty = null;
/**
* Template explicitly set to render in this view
* #var string
*/
protected $_customTemplate = '';
/**
* Smarty config
* #var array
*/
private $_config = null;
/**
* Class definition and constructor
*
* Let's start with the class definition and the constructor part. My class Travello_View_Smarty is extending the Zend_View_Abstract class. In the constructor the parent constructor from Zend_View_Abstract is called first. After that a Smarty object is instantiated, configured and stored in a private attribute.
* Please note that I use a configuration object from the object store to get the configuration data for Smarty.
*
* #param array $smartyConfig
* #param array $config
*/
public function __construct($smartyConfig, $config = array())
{
$this->_config = $smartyConfig;
parent::__construct($config);
$this->_loadSmarty();
}
/**
* Return the template engine object
*
* #return Smarty
*/
public function getEngine()
{
return $this->_smarty;
}
/**
* Implement _run() method
*
* The method _run() is the only method that needs to be implemented in any subclass of Zend_View_Abstract. It is called automatically within the render() method. My implementation just uses the display() method from Smarty to generate and output the template.
*
* #param string $template
*/
protected function _run()
{
$file = func_num_args() > 0 && file_exists(func_get_arg(0)) ? func_get_arg(0) : '';
if ($this->_customTemplate || $file) {
$template = $this->_customTemplate;
if (!$template) {
$template = $file;
}
$this->_smarty->display($template);
} else {
throw new Zend_View_Exception('Cannot render view without any template being assigned or file does not exist');
}
}
/**
* Overwrite assign() method
*
* The next part is an overwrite of the assign() method from Zend_View_Abstract, which works in a similar way. The big difference is that the values are assigned to the Smarty object and not to the $this->_vars variables array of Zend_View_Abstract.
*
* #param string|array $var
* #return Ext_View_Smarty
*/
public function assign($var, $value = null)
{
if (is_string($var)) {
$this->_smarty->assign($var, $value);
} elseif (is_array($var)) {
foreach ($var as $key => $value) {
$this->assign($key, $value);
}
} else {
throw new Zend_View_Exception('assign() expects a string or array, got '.gettype($var));
}
return $this;
}
public function display($template){
$this->clearVars();
$this->_smarty->display($template);
return $this;
}
/**
* Overwrite escape() method
*
* The next part is an overwrite of the escape() method from Zend_View_Abstract. It works both for string and array values and also uses the escape() method from the Zend_View_Abstract. The advantage of this is that I don't have to care about each value of an array to get properly escaped.
*
* #param mixed $var
* #return mixed
*/
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;
}
/**
* Print the output
*
* The next method output() is a wrapper on the render() method from Zend_View_Abstract. It just sets some headers before printing the output.
*
* #param <type> $name
*/
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);
}
/**
* Use Smarty caching
*
* The last two methods were created to simply integrate the Smarty caching mechanism in the View class. With the first one you can check for cached template and with the second one you can set the caching on or of.
*
* #param string $template
* #return bool
*/
public function isCached($template)
{
return $this->_smarty->is_cached($template);
}
/**
* Enable/disable caching
*
* #param bool $caching
* #return Ext_View_Smarty
*/
public function setCaching($caching)
{
$this->_smarty->caching = $caching;
return $this;
}
/**
* Template getter (return file path)
* #return string
*/
public function getTemplate()
{
return $this->_customTemplate;
}
/**
* Template filename setter
* #param string
* #return Ext_View_Smarty
*/
public function setTemplate($tpl)
{
$this->_customTemplate = $tpl;
return $this;
}
/**
* Magic setter for Zend_View compatibility. Performs assign()
*
* #param string $key
* #param mixed $val
*/
public function __set($key, $val)
{
$this->assign($key, $val);
}
/**
* Magic getter for Zend_View compatibility. Retrieves template var
*
* #param string $key
* #return mixed
*/
public function __get($key)
{
return $this->_smarty->getTemplateVars($key);
}
/**
* Magic getter for Zend_View compatibility. Removes template var
*
* #see View/Zend_View_Abstract::__unset()
* #param string $key
*/
public function __unset($key)
{
$this->_smarty->clearAssign($key);
}
/**
* Allows testing with empty() and isset() to work
* Zend_View compatibility. Checks template var for existance
*
* #param string $key
* #return boolean
*/
public function __isset($key)
{
return (null !== $this->_smarty->getTemplateVars($key));
}
/**
* Zend_View compatibility. Retrieves all template vars
*
* #see Zend_View_Abstract::getVars()
* #return array
*/
public function getVars()
{
return $this->_smarty->getTemplateVars();
}
/**
* Updates Smarty's template_dir field with new value
*
* #param string $dir
* #return Ext_View_Smarty
*/
public function setTemplateDir($dir)
{
$this->_smarty->setTemplateDir($dir);
return $this;
}
/**
* Adds another Smarty template_dir to scan for templates
*
* #param string $dir
* #return Ext_View_Smarty
*/
public function addTemplateDir($dir)
{
$this->_smarty->addTemplateDir($dir);
return $this;
}
/**
* Adds another Smarty plugin directory to scan for plugins
*
* #param string $dir
* #return Ext_View_Smarty
*/
public function addPluginDir($dir)
{
$this->_smarty->addPluginsDir($dir);
return $this;
}
/**
* Zend_View compatibility. Removes all template vars
*
* #see View/Zend_View_Abstract::clearVars()
* #return Ext_View_Smarty
*/
public function clearVars()
{
$this->_smarty->clearAllAssign();
$this->assign('this', $this);
return $this;
}
/**
* Zend_View compatibility. Add the templates dir
*
* #see View/Zend_View_Abstract::addBasePath()
* #return Ext_View_Smarty
*/
public function addBasePath($path, $classPrefix = 'Zend_View')
{
parent::addBasePath($path, $classPrefix);
$this->addScriptPath(PATH . '/templates/default');
$this->addTemplateDir(PATH . '/templates/shared');
return $this;
}
/**
* Zend_View compatibility. Set the templates dir instead of scripts
*
* #see View/Zend_View_Abstract::setBasePath()
* #return Ext_View_Smarty
*/
public function setBasePath($path, $classPrefix = 'Zend_View')
{
parent::setBasePath($path, $classPrefix);
$this->setScriptPath(PATH . '/templates/default');
$this->addTemplateDir(PATH . '/templates/shared');
return $this;
}
/**
* Magic clone method, on clone create diferent smarty object
*/
public function __clone() {
$this->_loadSmarty();
}
/**
* Initializes the smarty and populates config params
*
* #throws Zend_View_Exception
* #return void
*/
private function _loadSmarty()
{
if (!class_exists('Smarty', true)) {
require_once 'Smarty/Smarty.class.php';
}
$this->_smarty = new Smarty();
if ($this->_config === null) {
throw new Zend_View_Exception("Could not locate Smarty config - node 'smarty' not found");
}
$this->_smarty->caching = $this->_config['caching'];
$this->_smarty->cache_lifetime = $this->_config['cache_lifetime'];
$this->_smarty->template_dir = $this->_config['template_dir'];
$this->_smarty->compile_dir = $this->_config['compile_dir'];
$this->_smarty->config_dir = $this->_config['config_dir'];
$this->_smarty->plugins_dir = $this->_config['plugins_dir'];
$this->_smarty->cache_dir = $this->_config['cache_dir'];
$this->_smarty->left_delimiter = $this->_config['left_delimiter'];
$this->_smarty->right_delimiter = $this->_config['right_delimiter'];
$this->assign('this', $this);
}
}
There is Smarty implementation in Zend Documentation.
Smarty is bad, any template engine is bad and slowing down your application.
Use zend native views.
And remember that PHP is was invented to be a template engine.
http://framework.zend.com/manual/1.11/en/zend.view.scripts.html
When in your template, you write
{$this->layout()->content}
This is the content of the layout helper, that will render the view associated to each action.
When, in you controller, you write
$this->view->content = $this->view->display('contact/contact.tpl');
You assign a variable to your view, that can be display, using
{$content}
in your smarty template.
I think you have some confusion in your way of sorting this out. Have a look at
http://framework.zend.com/manual/1.12/en/zend.layout.quickstart.html
Anyway, your question is old and you already have selected an answer as correct, which was not really an answer by the way, but I couldn't pass by and say nothing. Using Smarty with Zend is great, Smarty is faster and compiling/caching have better fine tuning than Zend and the integration between both is neat (thanks to dependency injection). You can have the power of both libraries in one application, so go for it.

How do I set id prefixes used by Zend_View_Helper_Navigation_XXX

When I render a Zend_Nagivation instance in my view, by default the anchor tags have id's assigned with the prefix of the view helper, followed by a dash, and then the page's id.
Examples of Page 1's anchor id (all using the same Zend_Nagivation instance):
Zend_View_Helper_Navigation_Menu = "menu-1"
Zend_View_Helper_Navigation_Breadcrumbs = "breadcrumbs-1"
My_View_Helper_Navigation_MyMenu = "mymenu-1"
This is perfect for most cases, but I'd like to set that prefix manually, and I can't find a way to do it.
Solution
Specifying the prefix can be accomplished by adding the following code, and then calling setIdPrefix() when rendering:
class My_View_Helper_Navigation_MyMenu extends Zend_View_Helper_Navigation_Menu
{
protected $_idPrefix = null;
/**
* Set the id prefix to use for _normalizeId()
*
* #param string $prefix
* #return My_View_Helper_Navigation_MyMenu
*/
public function setIdPrefix($prefix)
{
if (is_string($prefix)) {
$this->_idPrefix = $prefix;
}
return $this;
}
/**
* Use the id prefix specified or proxy to the parent
*
* #param string $value
* #return string
*/
protected function _normalizeId($value)
{
if (is_null($this->_idPrefix)) {
return parent::_normalizeId($value);
} else {
return $this->_idPrefix . '-' . $value;
}
}
}
The culprit is Zend_View_Helper_Navigation_HelperAbstract::_normalizeId() for which I see no other solution than to create your own custom version of each navigation view helper you require.

Categories