i want to understand how this coding is working [php] - 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.

Related

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

Write output to console from helper class

I have a console command that runs a helper class and I want to write output with $this->info() to the console from the helper class.
My code looks like this:
App/Http/Console/Commands/SomeCommand.php
function handle(Helper $helper)
{
return $helper->somefunction();
}
App/Http/SomeHelper.php
function somefunction()
{
//some code
$this->info('send to console');
}
Is there any way to write the output to console from the helper?
I finally figured this out (works in Laravel 5.6)
In the handle() function of your SomeCommand class, add $this->myHelper->setConsoleOutput($this->getOutput());.
In your helper class, add:
/**
*
* #var \Symfony\Component\Console\Style\OutputStyle
*/
protected $consoleOutput;
/**
*
* #param \Symfony\Component\Console\Style\OutputStyle $consoleOutput
* #return $this
*/
public function setConsoleOutput($consoleOutput) {
$this->consoleOutput = $consoleOutput;
return $this;
}
/**
*
* #param string $text
* #return $this
*/
public function writeToOuput($text) {
if ($this->consoleOutput) {
$this->consoleOutput->writeln($text);
}
return $this;
}
/**
*
* #param string $text
* #return $this
*/
public function writeErrorToOuput($text) {
if ($this->consoleOutput) {
$style = new \Symfony\Component\Console\Formatter\OutputFormatterStyle('white', 'red', ['bold']); //white text on red background
$this->consoleOutput->getFormatter()->setStyle('error', $style);
$this->consoleOutput->writeln('<error>' . $text . '</error>');
}
return $this;
}
Then, anywhere else in your helper class, you can use:
$this->writeToOuput('Here is a string that I want to show in the console.');
You need to write $this->info('send to console'); this in SomeCommand.php file.For writing output follow this https://laravel.com/docs/5.2/artisan#writing-output
I have not tried, but maybe: $this->line("sent to console');

PHPunit File Testing

I'm relatively new to PHPUnit and TDD, and I was wondering how I might test the following code:
class File
{
/**
* Write data to a given file
*
* #param string $file
* #param string $content
* #return mixed
*/
public function put($path, $content)
{
return file_put_contents($path, $content);
}
}
How can I test if the file was created WITHOUT actually creating the file (with PHPUnit obviously).
Thanks.
You can mock the file system for your unit tests by using a virtual file system like vfsStream with documentation here
EDIT
An example would be something like:
class FileTest extends \PHPUnit_Framework_TestCase
{
/**
* #var vfsStreamDirectory
*/
private $root;
/**
* set up test environmemt
*/
public function setUp()
{
$this->root = vfsStream::setup('exampleDir');
}
/**
* test that the file is created
*/
public function testFileIsCreated()
{
$example = new File();
$filename = 'hello.txt';
$content = 'Hello world';
$this->assertFalse($this->root->hasChild($filename));
$example->put(vfsStream::url('exampleDir/' . $filename), $content);
$this->assertTrue($this->root->hasChild($filename));
}
}

Which is the best way to display 'flash messages' in kohana v3?

I would like to know the best way to display flash messages in Kohana v3?
Some tutorials or examples would be helpful.
Do you mean like Kohana 2.x's flash session variables?
The latest Kohana supports get_once() which is pretty similar to the old flash session variables.
$session = Session::instance();
$session->set('test', 'Hello, World!');
// The session variable is returned and removed.
$test = $session->get_once('test');
I think the get_once is a great function, but what if you want to keep the data actually separate from the regular data, here's a basic class that overloads "Session" so that you can use "codeigniter" style flashdata calls with any data-store.
<?php defined('SYSPATH') or die('No direct script access.');
abstract class Session extends Kohana_Session {
/**
* This calls the parent Kohana_Session constructor and processes
* new flashdata to flashdata, and flashdata to old flashdata
*
* #param array configuration
* #param string session id
* #return void
* #uses Kohana_Session::__construct
*/
public function __construct(array $config = NULL, $id = NULL)
{
parent::__construct($config,$id);
if(array_key_exists('___of',$this->_data)){
//Remove old Flash data
unset($this->_data['___of']);
}
if(array_key_exists('___flash',$this->_data)){
//Move current last requests flash data to old flash data
$this->_data['___of'] = $this->_data['___flash'];
unset($this->_data['___flash']);
}
if(array_key_exists('___nf',$this->_data)){
//Move Last Requests added data to the flash data
$this->_data['___flash'] = $this->_data['___nf'];
unset($this->_data['___nf']);
}
}
/**
* keeps a variable set in the sessions flashdata array.
*
* $session->set_flashdata('foo', 'bar');
*
* #param string variable name
* #param ...
* #return $this
*/
public function keep_flashdata($k)
{
$args = func_get_args();
if(array_key_exists('___of',$this->_data)){
foreach($args as $key){
if(array_key_exists($key,$this->_data['___of'])){
//So we were going to trash it...
$this->set_flashdata($k,$this->_data['___of'][$key],true);
}
}
}
$this->_data['___nf'][$key] = $value;
return $this;
}
/**
* Set a variable in the sessions flashdata array.
*
* $session->set_flashdata('foo', 'bar');
*
* #param string variable name
* #param mixed value
* #return $this
*/
public function set_flashdata($key, $value, $current=false)
{
if(!array_key_exists('___nf',$this->_data)){
$this->_data['___nf'] = array();
}
$this->_data['___nf'][$key] = $value;
if($current){
if(!array_key_exists('___flash',$this->_data)){
$this->_data['___flash'] = array();
}
$this->_data['flash'][$key] = $value;
}
return $this;
}
/**
* Set a variable by reference in the sessions flashdata array.
*
* $session->bind_flashdata('foo', $foo);
*
* #param string variable name
* #param mixed referenced value
* #return $this
*/
public function bind_flashdata($key, & $value)
{
if(!array_key_exists('___nf',$this->_data)){
$this->_data['___nf'] = array();
}
$this->_data['___nf'][$key] =& $value;
return $this;
}
/**
* Removes a variable in the session array.
*
* $session->delete_flashdata('foo');
*
* #param string variable name
* #param ...
* #return $this
*/
public function delete_flashdata($key)
{
$args = func_get_args();
if(array_key_exists('___nf',$this->_data)){
foreach ($args as $key)
{
if(array_key_exists($key,$this->_data['___nf'])){
unset($this->_data['___nf'][$key]);
}
}
}
return $this;
}
/**
* Get a variable from the sessions flashdata array.
*
* $foo = $session->get_flashdata('foo');
*
* #param string variable name
* #param mixed default value to return
* #return mixed
*/
public function get_flashdata($key, $default = NULL)
{
if(array_key_exists('___flash',$this->_data) && array_key_exists($key,$this->_data['___flash'])){
return $this->_data['___flash'][$key];
} else if(array_key_exists('___nf',$this->_data) && array_key_exists($key,$this->_data['___nf'])){
return $this->_data['___nf'][$key];
}
return $default;
}
/**
* Get and delete a variable from the session array.
*
* $bar = $session->get_once('bar');
*
* #param string variable name
* #param mixed default value to return
* #return mixed
*/
public function get_flashdata_once($key, $default = NULL)
{
$value = $this->get_flashdata($key, $default);
if(array_key_exists($key, $this->_data['___flash'])){
unset($this->_data['___flash'][$key]);
}
if(array_key_exists($key, $this->_data['___nf'])){
unset($this->_data['___nf'][$key]);
}
return $value;
}
}
?>
I realize there was an answer to this, and like i stated before, the get_once method is great and all, but i enjoy auto garbage collection much more.
If you have any improvements on this code, let me know, its been great to me so far.
Have a look at this module, it might be what you are looking for https://github.com/daveWid/message
I've written a really simple class for this once. Check it out below. Usage examples below
class Notice {
private static $session;
private static $initialized = false;
// current notices
private static $notices = array();
function __construct() {
}
static function init() {
self::$session = Session::instance();
self::$notices['current'] = json_decode(self::$session->get_once('flash'));
if(!is_array(self::$notices['current'])) self::$notices['current'] = array();
self::$initialized = true;
}
static function add($notice, $key=null) {
if(!self::$initialized) self::init();
if(!is_null($key)) {
self::$notices['new'][$key] = $notice;
} else {
self::$notices['new'][] = $notice;
}
self::$session->set('flash', json_encode(self::$notices['new']));
return true;
}
static function get($item = null) {
if(!self::$initialized) self::init();
if($item == null) {
return self::$notices['current'];
}
if(!array_key_exists($item, self::$notices['current']))
return null;
return self::$notices['current'][$item];
}
}
Examples (provided this class is saved as APPPATH . 'classes/notice.php'):
Notice::add('Something great has happened!');
Notice::add('Exciting! I\'ve got something to tell you!', 'message');
echo Notice::get('message'); // "Exciting! I've got ..."
foreach(Notice::get() as $message) {
echo $i++ . $message .'<br />';
}
EDIT: funny... for some reason this question popped up somewhere, didn't notice it was a really old one... sorry for that!
I am using https://github.com/synapsestudios/kohana-notices in my project and I am very happy with it.

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.

Categories