PHP in Template Class - php

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');

Related

How do I resolve Cannot use 'Object' as class name as it is reserved in C:\projectfolder\ckphp-demo\cake\libs\object.php on line 33

In working on a new cakephp application I get the error message Cannot use 'Object' as class name as it is reserved in C:\projectfolder\ckphp-demo\cake\libs\object.php on line 33.
The project is a legacy web application using cakePHP 1.3.17 with php version PHP 7.4.28 on developement server. see below code for object.php
line 33 is where class Object { starts
<?php
/**
* Object class, allowing __construct and __destruct in PHP4.
*
* Also includes methods for logging and the special method RequestAction,
* to call other Controllers' Actions from anywhere.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* #copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* #link http://cakephp.org CakePHP(tm) Project
* #package cake
* #subpackage cake.cake.libs
* #since CakePHP(tm) v 0.2.9
* #license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Object class, allowing __construct and __destruct in PHP4.
*
* Also includes methods for logging and the special method RequestAction,
* to call other Controllers' Actions from anywhere.
*
* #package cake
* #subpackage cake.cake.libs
*/
class Object {
/**
* A hack to support __construct() on PHP 4
* Hint: descendant classes have no PHP4 class_name() constructors,
* so this constructor gets called first and calls the top-layer __construct()
* which (if present) should call parent::__construct()
*
* #return Object
*/
function Object() {
$args = func_get_args();
if (method_exists($this, '__destruct')) {
register_shutdown_function (array(&$this, '__destruct'));
}
call_user_func_array(array(&$this, '__construct'), $args);
}
/**
* Class constructor, overridden in descendant classes.
*/
function __construct() {
}
/**
* Object-to-string conversion.
* Each class can override this method as necessary.
*
* #return string The name of this class
* #access public
*/
function toString() {
$class = get_class($this);
return $class;
}
/**
* Calls a controller's method from any location. Can be used to connect controllers together
* or tie plugins into a main application. requestAction can be used to return rendered views
* or fetch the return value from controller actions.
*
* #param mixed $url String or array-based url.
* #param array $extra if array includes the key "return" it sets the AutoRender to true.
* #return mixed Boolean true or false on success/failure, or contents
* of rendered action if 'return' is set in $extra.
* #access public
*/
function requestAction($url, $extra = array()) {
if (empty($url)) {
return false;
}
if (!class_exists('dispatcher')) {
require CAKE . 'dispatcher.php';
}
if (in_array('return', $extra, true)) {
$extra = array_merge($extra, array('return' => 0, 'autoRender' => 1));
}
if (is_array($url) && !isset($extra['url'])) {
$extra['url'] = array();
}
$params = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
$dispatcher = new Dispatcher;
return $dispatcher->dispatch($url, $params);
}
/**
* Calls a method on this object with the given parameters. Provides an OO wrapper
* for `call_user_func_array`
*
* #param string $method Name of the method to call
* #param array $params Parameter list to use when calling $method
* #return mixed Returns the result of the method call
* #access public
*/
function dispatchMethod($method, $params = array()) {
switch (count($params)) {
case 0:
return $this->{$method}();
case 1:
return $this->{$method}($params[0]);
case 2:
return $this->{$method}($params[0], $params[1]);
case 3:
return $this->{$method}($params[0], $params[1], $params[2]);
case 4:
return $this->{$method}($params[0], $params[1], $params[2], $params[3]);
case 5:
return $this->{$method}($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array(array(&$this, $method), $params);
break;
}
}
/**
* Stop execution of the current script. Wraps exit() making
* testing easier.
*
* #param $status see http://php.net/exit for values
* #return void
* #access public
*/
function _stop($status = 0) {
exit($status);
}
/**
* Convience method to write a message to CakeLog. See CakeLog::write()
* for more information on writing to logs.
*
* #param string $msg Log message
* #param integer $type Error type constant. Defined in app/config/core.php.
* #return boolean Success of log write
* #access public
*/
function log($msg, $type = LOG_ERROR) {
if (!class_exists('CakeLog')) {
require LIBS . 'cake_log.php';
}
if (!is_string($msg)) {
$msg = print_r($msg, true);
}
return CakeLog::write($type, $msg);
}
/**
* Allows setting of multiple properties of the object in a single line of code. Will only set
* properties that are part of a class declaration.
*
* #param array $properties An associative array containing properties and corresponding values.
* #return void
* #access protected
*/
function _set($properties = array()) {
if (is_array($properties) && !empty($properties)) {
$vars = get_object_vars($this);
foreach ($properties as $key => $val) {
if (array_key_exists($key, $vars)) {
$this->{$key} = $val;
}
}
}
}
/**
* Used to report user friendly errors.
* If there is a file app/error.php or app/app_error.php this file will be loaded
* error.php is the AppError class it should extend ErrorHandler class.
*
* #param string $method Method to be called in the error class (AppError or ErrorHandler classes)
* #param array $messages Message that is to be displayed by the error class
* #return error message
* #access public
*/
function cakeError($method, $messages = array()) {
if (!class_exists('ErrorHandler')) {
App::import('Core', 'Error');
if (file_exists(APP . 'error.php')) {
include_once (APP . 'error.php');
} elseif (file_exists(APP . 'app_error.php')) {
include_once (APP . 'app_error.php');
}
}
if (class_exists('AppError')) {
$error = new AppError($method, $messages);
} else {
$error = new ErrorHandler($method, $messages);
}
return $error;
}
/**
* Checks for a persistent class file, if found file is opened and true returned
* If file is not found a file is created and false returned
* If used in other locations of the model you should choose a unique name for the persistent file
* There are many uses for this method, see manual for examples
*
* #param string $name name of the class to persist
* #param string $object the object to persist
* #return boolean Success
* #access protected
* #todo add examples to manual
*/
function _persist($name, $return = null, &$object, $type = null) {
$file = CACHE . 'persistent' . DS . strtolower($name) . '.php';
if ($return === null) {
if (!file_exists($file)) {
return false;
} else {
return true;
}
}
if (!file_exists($file)) {
$this->_savePersistent($name, $object);
return false;
} else {
$this->__openPersistent($name, $type);
return true;
}
}
/**
* You should choose a unique name for the persistent file
*
* There are many uses for this method, see manual for examples
*
* #param string $name name used for object to cache
* #param object $object the object to persist
* #return boolean true on save, throws error if file can not be created
* #access protected
*/
function _savePersistent($name, &$object) {
$file = 'persistent' . DS . strtolower($name) . '.php';
$objectArray = array(&$object);
$data = str_replace('\\', '\\\\', serialize($objectArray));
$data = '<?php $' . $name . ' = \'' . str_replace('\'', '\\\'', $data) . '\' ?>';
$duration = '+999 days';
if (Configure::read() >= 1) {
$duration = '+10 seconds';
}
cache($file, $data, $duration);
}
/**
* Open the persistent class file for reading
* Used by Object::_persist()
*
* #param string $name Name of persisted class
* #param string $type Type of persistance (e.g: registry)
* #return void
* #access private
*/
function __openPersistent($name, $type = null) {
$file = CACHE . 'persistent' . DS . strtolower($name) . '.php';
include($file);
switch ($type) {
case 'registry':
$vars = unserialize(${$name});
foreach ($vars['0'] as $key => $value) {
if (strpos($key, '_behavior') !== false) {
App::import('Behavior', Inflector::classify(substr($key, 0, -9)));
} else {
App::import('Model', Inflector::camelize($key));
}
unset ($value);
}
unset($vars);
$vars = unserialize(${$name});
foreach ($vars['0'] as $key => $value) {
ClassRegistry::addObject($key, $value);
unset ($value);
}
unset($vars);
break;
default:
$vars = unserialize(${$name});
$this->{$name} = $vars['0'];
unset($vars);
break;
}
}
}

i want to understand how this coding is working [php]

this is the tpl file used show GUI of something. i posted it all. how this code read the tpl file and show HTML display. which command is doing this.
class Template {
/**
* Config
*
* #access private
*/
private static $config;
/**
* Path templates
*
* #access private
*/
private $tpl_path = null;
/**
* Values
*
* #access private
*/
private $values = array();
/**
* Constructor
*
* #access public
*/
public function __construct($tpl_path) {
self::$config = config_load('template');
$this->tpl_path = $tpl_path;
}
/**
* Set a template variable
*
* #access public
*/
public function set($name, $value = null) {
if(is_array($name)) {
foreach ($name as $key => $value) {
$this->values[$key] = $value;
}
} else {
$this->values[$name] = $value;
}
}
/**
* Display the template file
*
* #access public
*/
public function display($template) {
if ($this->values) {
extract($this->values);
}
if (file_exists($this->tpl_path . $template . self::$config['template_extension'])) {
ob_start();
include($this->tpl_path . $template . self::$config['template_extension']);
$output = ob_get_contents();
ob_end_clean();
} else {
die('Template file '. $this->tpl_path . $template . self::$config['template_extension'] . ' not found.');
}
if ($output) echo $output;
}
}
?>
i have the file which is using this class and the code is
$tpl->set('customer_details', $customer_details);
$tpl->set('customer_addresses', $customer_addresses);
$tpl->set('countries', $countries);
//Display the template
$tpl->display('edit_account');
the above code is using tpl and setting values. but how the values are set and displayed
It's very simple. The class code uses php include. The templates can freely intermix php and HTML just as any php file can, and variables will be interpolated. The class uses output buffering to store the output and then using echo returns the output. Variables used in the class are provided generically using the set method that puts them all into a class array variable named 'values' which is undoubtably referenced in the template files.

Extending a class which has static methods

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;
}
...
}

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.

getting RSS feeds on website

I had this code that I wrote last year and it returns RSS feeds for some term I enter:
<html>
<body>
<form name="form" action="search.php" method="get">
<input type="text" name="q" />
<input type="submit" name="Submit" value="Search" />
</form>
<?php
require_once "RSS.php";
// want to parse the $row[1] variable to get out words, make new string with a + instead of spaces
$college = "college";
$collegelen= strlen($college);
for($i = 0; $i < $collegelen; $i++){
if ($college{$i} == " ")
{$spaced = $spaced . "+";}
else
{$spaced = $spaced . $college{$i};}
}
echo("Yahoo! News RSS");
$rss_yahoo =& new XML_RSS("http://news.search.yahoo.com/news/rss?p=" . $spaced . "&ei=UTF-8&fl=0&x=wrt");
$rss_yahoo->parse();
foreach ($rss_yahoo->getItems() as $item) {
echo "<li>" . $item['title'] . "</li><br>";
//echo $item['pubDate'] ."<br>";
echo $item['description'] . "<br><br>\n"; }
//echo("Google RSS");
//$rss_google =& new XML_RSS("http://news.google.com/news?hl=en&ned=us&q=" . $spaced . "&ie=UTF-8&nolr=1&output=rss");
//$rss_google->parse();
//foreach ($rss_google->getItems() as $item) {
// echo "<li>" . $item['title'] . "</li><br>";
// echo $item['description'] . "<br><br>\n"; }
echo("Google RSS");
$rss_google =& new XML_RSS("http://news.google.com/news?hl=en&ned=us&q=" . $spaced . "&ie=UTF-8&nolr=1&output=rss");
$rss_google->parse();
foreach ($rss_google->getItems() as $item) {
echo "<li>" . $item['title'] . "</li><br>";
- Hide quoted text -
"<br><br>\n"; }
?>
</body>
</html>
RSS.php
<?php
// vim: set expandtab tabstop=4 shiftwidth=4 fdm=marker:
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license#php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Martin Jansen <mj#php.net> |
// | |
// +----------------------------------------------------------------------+
//
// $Id: RSS.php,v 1.28 2006/09/14 08:40:05 clay Exp $
//
require_once 'Parser.php';
/**
* RSS parser class.
*
* This class is a parser for Resource Description Framework (RDF) Site
* Summary (RSS) documents. For more information on RSS see the
* website of the RSS working group (http://www.purl.org/rss/).
*
* #author Martin Jansen <mj#php.net>
* #version $Revision: 1.28 $
* #access public
*/
class XML_RSS extends XML_Parser
{
// {{{ properties
/**
* #var string
*/
var $insideTag = '';
/**
* #var array
*/
var $insideTagStack = array();
/**
* #var string
*/
var $activeTag = '';
/**
* #var array
*/
var $channel = array();
/**
* #var array
*/
var $items = array();
/**
* #var array
*/
var $item = array();
/**
* #var array
*/
var $image = array();
/**
* #var array
*/
var $textinput = array();
/**
* #var array
*/
var $textinputs = array();
/**
* #var array
*/
var $attribs;
/**
* #var array
*/
var $parentTags = array('CHANNEL', 'ITEM', 'IMAGE', 'TEXTINPUT');
/**
* #var array
*/
var $channelTags = array('TITLE', 'LINK', 'DESCRIPTION', 'IMAGE',
'ITEMS', 'TEXTINPUT', 'LANGUAGE', 'COPYRIGHT',
'MANAGINGEditor', 'WEBMASTER', 'PUBDATE', 'LASTBUILDDATE',
'CATEGORY', 'GENERATOR', 'DOCS', 'CLOUD', 'TTL',
'RATING');
/**
* #var array
*/
var $itemTags = array('TITLE', 'LINK', 'DESCRIPTION', 'PUBDATE', 'AUTHOR', 'CATEGORY',
'COMMENTS', 'ENCLOSURE', 'GUID', 'PUBDATE', 'SOURCE',
'CONTENT:ENCODED');
/**
* #var array
*/
var $imageTags = array('TITLE', 'URL', 'LINK', 'WIDTH', 'HEIGHT');
var $textinputTags = array('TITLE', 'DESCRIPTION', 'NAME', 'LINK');
/**
* List of allowed module tags
*
* Currently supported:
*
* Dublin Core Metadata
* blogChannel RSS module
* CreativeCommons
* Content
* Syndication
* Trackback
* GeoCoding
* Media
* iTunes
*
* #var array
*/
var $moduleTags = array('DC:TITLE', 'DC:CREATOR', 'DC:SUBJECT', 'DC:DESCRIPTION',
'DC:PUBLISHER', 'DC:CONTRIBUTOR', 'DC:DATE', 'DC:TYPE',
'DC:FORMAT', 'DC:IDENTIFIER', 'DC:SOURCE', 'DC:LANGUAGE',
'DC:RELATION', 'DC:COVERAGE', 'DC:RIGHTS',
'BLOGCHANNEL:BLOGROLL', 'BLOGCHANNEL:MYSUBSCRIPTIONS',
'BLOGCHANNEL:BLINK', 'BLOGCHANNEL:CHANGES',
'CREATIVECOMMONS:LICENSE', 'CC:LICENSE', 'CONTENT:ENCODED',
'SY:UPDATEPERIOD', 'SY:UPDATEFREQUENCY', 'SY:UPDATEBASE',
'TRACKBACK:PING', 'GEO:LAT', 'GEO:LONG',
'MEDIA:GROUP', 'MEDIA:CONTENT', 'MEDIA:ADULT',
'MEDIA:RATING', 'MEDIA:TITLE', 'MEDIA:DESCRIPTION',
'MEDIA:KEYWORDS', 'MEDIA:THUMBNAIL', 'MEDIA:CATEGORY',
'MEDIA:HASH', 'MEDIA:PLAYER', 'MEDIA:CREDIT',
'MEDIA:COPYRIGHT', 'MEDIA:TEXT', 'MEDIA:RESTRICTION',
'ITUNES:AUTHOR', 'ITUNES:BLOCK', 'ITUNES:CATEGORY',
'ITUNES:DURATION', 'ITUNES:EXPLICIT', 'ITUNES:IMAGE',
'ITUNES:KEYWORDS', 'ITUNES:NEW-FEED-URL', 'ITUNES:OWNER',
'ITUNES:PUBDATE', 'ITUNES:SUBTITLE', 'ITUNES:SUMMARY'
);
/**
* #var array
*/
var $last = array();
// }}}
// {{{ Constructor
/**
* Constructor
*
* #access public
* #param mixed File pointer, name of the RSS file, or an RSS string.
* #param string Source charset encoding, use null (default) to use
* default encoding (ISO-8859-1)
* #param string Target charset encoding, use null (default) to use
* default encoding (ISO-8859-1)
* #return void
*/
function XML_RSS($handle = '', $srcenc = null, $tgtenc = null)
{
if ($srcenc === null && $tgtenc === null) {
$this->XML_Parser();
} else {
$this->XML_Parser($srcenc, 'event', $tgtenc);
}
$this->setInput($handle);
if ($handle == '') {
$this->raiseError('No input passed.');
}
}
// }}}
// {{{ startHandler()
/**
* Start element handler for XML parser
*
* #access private
* #param object XML parser object
* #param string XML element
* #param array Attributes of XML tag
* #return void
*/
function startHandler($parser, $element, $attribs)
{
if (substr($element, 0, 4) == "RSS:") {
$element = substr($element, 4);
}
switch ($element) {
case 'CHANNEL':
case 'ITEM':
case 'IMAGE':
case 'TEXTINPUT':
$this->insideTag = $element;
array_push($this->insideTagStack, $element);
break;
case 'ENCLOSURE' :
$this->attribs = $attribs;
break;
default:
$this->activeTag = $element;
}
}
// }}}
// {{{ endHandler()
/**
* End element handler for XML parser
*
* If the end of <item>, <channel>, <image> or <textinput>
* is reached, this method updates the structure array
* $this->struct[] and adds the field "type" to this array,
* that defines the type of the current field.
*
* #access private
* #param object XML parser object
* #param string
* #return void
*/
function endHandler($parser, $element)
{
if (substr($element, 0, 4) == "RSS:") {
$element = substr($element, 4);
}
if ($element == $this->insideTag) {
array_pop($this->insideTagStack);
$this->insideTag = end($this->insideTagStack);
$this->struct[] = array_merge(array('type' => strtolower($element)),
$this->last);
}
if ($element == 'ITEM') {
$this->items[] = $this->item;
$this->item = '';
}
if ($element == 'IMAGE') {
$this->images[] = $this->image;
$this->image = '';
}
if ($element == 'TEXTINPUT') {
$this->textinputs = $this->textinput;
$this->textinput = '';
}
if ($element == 'ENCLOSURE') {
if (!isset($this->item['enclosures'])) {
$this->item['enclosures'] = array();
}
$this->item['enclosures'][] = array_change_key_case($this->attribs, CASE_LOWER);
$this->attribs = array();
}
$this->activeTag = '';
}
// }}}
// {{{ cdataHandler()
/**
* Handler for character data
*
* #access private
* #param object XML parser object
* #param string CDATA
* #return void
*/
function cdataHandler($parser, $cdata)
{
if (in_array($this->insideTag, $this->parentTags)) {
$tagName = strtolower($this->insideTag);
$var = $this->{$tagName . 'Tags'};
if (in_array($this->activeTag, $var) ||
in_array($this->activeTag, $this->moduleTags)) {
$this->_add($tagName, strtolower($this->activeTag),
$cdata);
}
}
}
// }}}
// {{{ defaultHandler()
/**
* Default handler for XML parser
*
* #access private
* #param object XML parser object
* #param string CDATA
* #return void
*/
function defaultHandler($parser, $cdata)
{
return;
}
// }}}
// {{{ _add()
/**
* Add element to internal result sets
*
* #access private
* #param string Name of the result set
* #param string Fieldname
* #param string Value
* #return void
* #see cdataHandler
*/
function _add($type, $field, $value)
{
if (empty($this->{$type}) || empty($this->{$type}[$field])) {
$this->{$type}[$field] = $value;
} else {
$this->{$type}[$field] .= $value;
}
$this->last = $this->{$type};
}
// }}}
// {{{ getStructure()
/**
* Get complete structure of RSS file
*
* #access public
* #return array
*/
function getStructure()
{
return (array)$this->struct;
}
// }}}
// {{{ getchannelInfo()
/**
* Get general information about current channel
*
* This method returns an array containing the information
* that has been extracted from the <channel>-tag while parsing
* the RSS file.
*
* #access public
* #return array
*/
function getChannelInfo()
{
return (array)$this->channel;
}
// }}}
// {{{ getItems()
/**
* Get items from RSS file
*
* This method returns an array containing the set of items
* that are provided by the RSS file.
*
* #access public
* #return array
*/
function getItems()
{
return (array)$this->items;
}
// }}}
// {{{ getImages()
/**
* Get images from RSS file
*
* This method returns an array containing the set of images
* that are provided by the RSS file.
*
* #access public
* #return array
*/
function getImages()
{
return (array)$this->images;
}
// }}}
// {{{ getTextinputs()
/**
* Get text input fields from RSS file
*
* #access public
* #return array
*/
function getTextinputs()
{
return (array)$this->textinputs;
}
// }}}
}
?>
However, this code doesn't work anymore or I am not testing it correctly...I am running it on xampp on mac.
I wanted to make something like this:
The user enters a term and I want to display the RSS feeds from Yahoo, Google or NYTimes.
Thanks!
EDIT: I got two files RSS.php and Parser.php from a site last year and now it looks like the site is down. I am trying to see if anyone can offer another solution. Thanks!
Maybe you could try SimplePie. It's easy to use and have active development. You can start using right away, or reading the documentation for more advance usage.

Categories