So I'm using the following output method to output a file called profile-card.php inside my template directory.
public function output()
{
ob_start();
$profile = $this;
include $_SERVER['DOCUMENT_ROOT'] . '/wp-content/mu-plugins/s/templates/profile-card.php';
$output = ob_get_clean();
return $output;
}
So instead of having that method output all that code, I want to convert is to something like this where I can just call a string on the filename and it will render the template:
public function output()
{
return Template::load($this, 'profile-card');
}
What would be a good start/approach to tackle this? I have my Template::load() method setup with the following:
class Template
{
public function __construct()
{
// #todo: Initialize the object's methods
}
public static function init()
{
// #todo: Build out the template from the directory
}
public static function load()
{
// #todo: Add in more code in here
}
}
You could have a simple method taking a path and an array of parameters to pass to your view:
class Template
{
private const PATH_FROM_DOCUMENT_ROOT = '/wp-content/mu-plugins/s/templates';
public static function show(string $path, array $params = []): string
{
ob_start();
extract($params, EXTR_OVERWRITE);
require $_SERVER['DOCUMENT_ROOT'] . self::PATH_FROM_DOCUMENT_ROOT . $path . '.php';
return ob_get_clean();
}
}
Usage:
Template::show('profile-card', ['profile' => $profile]);
// ^ $this, in your case
Demo: https://3v4l.org/NEt4r (non-working there for obvious reasons, but shows a full sample)
Note: using a static method for this is probably not the greatest idea (I'd go as far as say it's to be avoided in general, but that's another discussion). I've kept this sample very basic to give you the general idea.
Related
I have written some Web Framework in PHP. I was been advised to do nothing in static Context. But i have some Question about this.
Imagine the following Class:
class Image extends HtmlControl {
public $src;
public $alt;
function getDetailPath()
{
return 'Common/Image';
}
}
It is nothing special. It is a Class to render an Image in Html. My Base Class has current following Implementation:
abstract class HtmlControl {
private $template;
abstract function getDetailPath();
public function __construct(ViewInformation $viewInformation) {
$this->template = 'foo/bar/' . $viewInformation->getEndpoint() . '/' . $this->getDetailPath() . '.php';
}
public function render() {
$output = '';
//Load template end fill $output
return $output;
}
}
Also nothing Special. It basicly will resolve the Endpoint Type (something like Frontend or Backend) to the corresponding template file, and provide the method render to get the output.
The Problem is, i need everytime for each part of a html controll to give the $viewInformation parameter.
$img = new Image($this->_info);
In my opinion something like this would be much nicer:
$img = new Image();
So i would have to save the State, which Endpoint should be used, in a static Context. Something like this (Note the Request::getEndpoint() Part):
abstract class HtmlControl {
private $template;
abstract function getDetailPath();
public function render() {
$template = 'foo/bar/' . Request::getEndpoint() . '/' . $this->getDetailPath() . '.php';
$output = '';
//Load template end fill $output
return $output;
}
}
My Question: Is it in this case okay, to have the endpoint in a static context? If not, could my current implementation improved?
I'm new to PHP "class". I'm looking for a script that can help me create PHP templates, I found this one but I can't seem to understand what is happening here. Can anyone please explain in details. I will be very grateful. Thanks..
<?php
class skin {
var $filename;
public function __construct($filename) {
$this->filename = $filename;
}
public function mk($filename) {
$this->filename = $filename;
return $this->make();
}
public function make() {
global $CONF;
$file = sprintf('./'.$CONF['theme_path'].'/'.$CONF['theme_name'].'/html/%s.html', $this->filename);
$fh_skin = fopen($file, 'r');
$skin = #fread($fh_skin, filesize($file));
fclose($fh_skin);
return $this->parse($skin);
}
private function parse($skin) {
global $TMPL, $LNG;
$skin = preg_replace_callback('/{\$lng->(.+?)}/i', create_function('$matches', 'global $LNG; return $LNG[$matches[1]];'), $skin);
$skin = preg_replace_callback('/{\$([a-zA-Z0-9_]+)}/', create_function('$matches', 'global $TMPL; return (isset($TMPL[$matches[1]])?$TMPL[$matches[1]]:"");'), $skin);
return $skin;
}
}
?>
At the beginning of the class __construct() assigns the filename to a variable so to be used everywhere in the class ($filename).
Then there is a function that parse it parse().
But this function is nested into another function for technical purposes. the private keyword before parse() means it could be used by the class itself.
Hence, the function make() is responsible for making use of parse();
A final function mk() calls make().
parse() parses the template. Means it replaces the actual final parsed variables and data with the template special syntax (which you must refer to in your template file).
make() function gets the content of the file and printf() in it generates a usable full URL from the given params to it.
I'm just very slowly starting to sink into object-oriented programming, so please be gentle on me.
I have a custom class for Smarty that was partially borrowed. This is how the only example reflects the basic idea of using it across my current project:
class Template {
function Template() {
global $Smarty;
if (!isset($Smarty)) {
$Smarty = new Smarty;
}
}
public static function display($filename) {
global $Smarty;
if (!isset($Smarty)) {
Template::create();
}
$Smarty->display($filename);
}
Then in the PHP, I use the following to display templates based on the above example:
Template::display('head.tpl');
Template::display('category.tpl');
Template::display('footer.tpl');
I made the following example of code (see below) work across universally, so I wouldn't repeat the above lines (see 3 previous lines) all the time in each PHP file.
I would just like to set, e.g.:
Template::defauls();
that would load:
Template::display('head.tpl');
Template::display('template_name_that_would_correspond_with_php_file_name.tpl');
Template::display('footer.tpl');
As you can see Template::display('category.tpl'); will always be changing based on the PHP file, which name is corresponded with the template name, meaning, if for example, PHP file is named stackoverflow.php then the template for it would be stackoverflow.tpl.
I've tried my solution that have worked fine but I don't like it the way it looks (the way it's structured).
What I did was:
Assigned in config a var and called it $current_page_name (that derives the current PHP page name, like this: basename($_SERVER['PHP_SELF'], ".php"); ), which returned, for e.g.: category.
In PHP file I used Template::defaults($current_page_name);
In my custom Smarty class I added the following:
public static function defaults($template) {
global $Smarty;
global $msg;
global $note;
global $attention;
global $err;
if (!isset($Smarty)) {
Templates::create();
}
Templates::assign('msg', $msg);
Templates::assign('note', $note);
Templates::assign('attention', $attention);
Templates::assign('err', $err);
Templates::display('head.tpl');
Templates::display($template . '.tpl');
Templates::display('footer.tpl');
}
Is there a way to make it more concise and well structured? I know about Code Review but I would like you, guys, to take a good look at it.
This looks like you haven't loaded Smarty, that's why the error happens. You need to start by including Smarty before the class starts. If you follow my other config suggestion you should start by including that one as well.
In you Template class, just add the following function:
function defaults() {
// Don't know if you need the assignes, havn't used Smarty, but if so, insert them here...
Template::display( Config::get('header_template') ); //header_template set in the Config file
Template::display( basename($_SERVER['PHP_SELF'], ".php") . '.tpl' );
Template::display( Config::get('footer_template') ); //footer_template set in the Config file
}
Now you should be able to use it in any file:
$template = new Template();
$template->defaults();
EDIT:
A singleton is in every sense the same as a global, that will keep your same problem.
But your problem is that if you try to use one of the Template's static functions you are in the "static" mode, which means the constructor have not been run. And Smarty has not been assigned. If you want to go this road, you can do one of two thinks:
Make the Template a real singleton, meaning set the constructor to private add a function getInstance, that returns a instance of the class, and then use that object to call the functions in it (which should not be static), or
Make all those static functions check if smarty is set, and if it's not, create a new instance of smarty, otherwise use the one that already is instantiated to run its function.
EDIT 2:
Here's the proper way to make a singleton:
class Singleton {
private static $instance = null;
// private static $smarty = null;
private function __construct() {
//self::$smarty = new Smarty();
}
public static function getInstance() {
if( self::$instance === null ) {
self::$instance = self();
}
return self::$instance;
}
public function doSomething() {
//self::$smarty->doSomething();
}
}
It's used like this:
$singleton = Singletong::getInstance();
$singleton->doSomething();
I commented out the things you probably want do to to make this a singleton wrapper around a singleton Smarty object. Hope this helps.
EDIT 3:
Here's a working copy of your code:
class Template {
private static $smarty_instance;
private static $template_instance;
private function Template() {
self::$smarty_instance = new Smarty();
$this->create();
}
public static function getInstance() {
if( ! isset( self::$template_instance ) ) {
self::$template_instance = new self();
}
return self::$template_instance;
}
private function create() {
self::$smarty_instance->compile_check = true;
self::$smarty_instance->debugging = false;
self::$smarty_instance->compile_dir = "/home/docs/public_html/domain.org/tmp/tpls";
self::$smarty_instance->template_dir = "/home/docs/public_html/domain.org";
return true;
}
public function setType($type) {
self::$smarty_instance->type = $type;
}
public function assign($var, $value) {
self::$smarty_instance->assign($var, $value);
}
public function display($filename) {
self::$smarty_instance->display($filename);
}
public function fetch($filename) {
return self::$smarty_instance->fetch($filename);
}
public function defaults($filename) {
global $user_message;
global $user_notification;
global $user_attention;
global $user_error;
self::$smarty_instance->assign('user_message', $user_message);
self::$smarty_instance->assign('user_notification', $user_notification);
self::$smarty_instance->assign('user_attention', $user_attention);
self::$smarty_instance->assign('user_error', $user_error);
self::$smarty_instance->assign('current_page', $filename);
self::$smarty_instance->display('head.tpl');
self::$smarty_instance->display($filename . '.tpl');
self::$smarty_instance->display('footer.tpl');
}
}
When using this function, you should use it like this:
$template = Template::getInstance();
$template->defaults($filename);
Try it now.
You can get current file name in your defaults() function. Use this piece of code:
$currentFile = $_SERVER['REQUEST_URI'];
$parts = explode('/', $currentFile);
$fileName = array_pop($parts);
$viewName = str_replace('.php', '.tpl', $fileName);
$viewName is the name that you need.
This is a quick wrapper I made for Smarty, hope it gives you some ideas
class Template extends Smarty
{
public $template = null;
public $cache = null;
public $compile = null;
public function var($name, $value, $cache)
{
$this->assign($name, $value, $cache);
}
public function render($file, $extends = false)
{
$this->prep();
$pre = null;
$post = null;
if ($extends)
{
$pre = 'extends:';
$post = '|header.tpl|footer.tpl';
}
if ($this->prep())
{
return $this->display($pre . $file . $post);
}
}
public function prep()
{
if (!is_null($this->template))
{
$this->setTemplateDir($this->template);
return true;
}
if (!is_null($this->cache))
{
$this->setCacheDir($this->cache);
}
if (!is_null($this->compile))
{
$this->setCompileDir($this->compile);
return true;
}
return false;
}
}
Then you can use it like this
$view = new Template();
$view->template = 'path/to/template/';
$view->compile = 'path/to/compile/'
$view->cache = 'path/to/cache';
$view->assign('hello', 'world');
// or
$view->var('hello', 'world');
$view->render('index.tpl');
//or
$view->render('index.tpl', true); // for extends functionality
I did this kinda fast, but just to show you the basic ways you can use smarty. In a more complete version you could probably want to check to see if compile dir is writable, or if file templates exist etc.
After trying for few days to solve this simple problem, I have finally came up with working and fully satisfying solution. Remember, I'm just a newby in object-oriented programming and that's the main reason why it took so long.
My main idea was not to use global $Smarty in my initial code that worked already fine. I like to use my Smarty as just simple as entering, e.g.: Template::assign('array', $array). To display defaults, I came up with the trivial solution (read my initial post), where now it can be just used Template::defaults(p()); to display or assign anything that is repeated on each page of your project.
For doing that, I personally stopped on the following fully working solution:
function p() {
return basename($_SERVER['PHP_SELF'], ".php");
}
require('/smarty/Smarty.class.php');
class Template
{
private static $smarty;
static function Smarty()
{
if (!isset(self::$smarty)) {
self::$smarty = new Smarty();
self::Smarty()->compile_check = true;
self::Smarty()->debugging = false;
self::Smarty()->plugins_dir = array(
'/home/docs/public_html/domain.com/smarty/plugins',
'/home/docs/public_html/domain.com/extensions/smarty');
self::Smarty()->compile_dir = "/home/docs/public_html/domain.com/cache";
self::Smarty()->template_dir = "/home/docs/public_html/domain.org";
}
return self::$smarty;
}
public static function setType($type)
{
self::Smarty()->type = $type;
}
public static function assign($var, $value)
{
self::Smarty()->assign($var, $value);
}
public static function display($filename)
{
self::Smarty()->display($filename);
}
public static function fetch($filename)
{
self::Smarty()->fetch($filename);
}
public static function defaults($filename)
{
Template::assign('current_page_name', $filename);
Template::display('head.tpl');
Template::display($filename . '.tpl');
Template::display('footer.tpl');
}
}
Please use it if you like it in your projects but leave comments under this post if you think I could improve it or you have any suggestions.
Initial idea of doing all of that was learning and exercising in writing a PHP code in object-oriented style.
When I call any function without recursion (class is loaded by SPL) - all fine, but if that function is calling itself (recursion) - nothing works.
If I use function without autoloader - all works great. I think that happens because object of class doesn't exist, like with magic methods: you have to use __callStatic, not a __call with abstract using class, I was trying to make this function static oO but nothing works again.
Any ideas how does it possible to use recursion through autoloader?
For example this function from php.net doesn't work in autoloader mode:
function r_implode($glue, $pieces)
{
foreach ($pieces as $r_pieces)
{
if (is_array( $r_pieces ))
{
$r_pieces = r_implode($glue, $r_pieces);
}
else
{
$retVal[] = $r_pieces;
}
}
return implode($glue, $retVal);
}
class load
{
public static function init()
{
return spl_autoload_register(array(__CLASS__, "hook"));
}
public static function quit()
{
return spl_autoload_unregister(array(__CLASS__, "hook"));
}
public static function hook($class)
{
// echo "CLASS IS:$class<br>";
$lnk=PATH . str_replace("_", "/", $class) . ".php";
ob_start();
require $lnk;
ob_end_clean();
return $class;
}
}
So when I add function into a class tools, and call tools::r_implode($a,$b); function doesn't work, but when I insert this function in the same php and call r_implode($a,$b) works.
From your posted info this is not clear. You didn't describe the actual error. But I surmise your problem is actually this:
class tools {
function r_implode($glue, $pieces)
{
$r_pieces = r_implode($glue, $r_pieces);
}
}
You have packed that function into a class, and the autoloader may even find it. But you didn't adapt the recursive call. If you don't use tools::r_implode for the recursion, then PHP won't find that function. Static methods need to be named explicitly (with class:: prefix). Keeping the plain function name there won't work.
I'm trying to whip up a skeleton View system in PHP, but I can't figure out how to get embedded views to receive their parent's variables. For example:
View Class
class View
{
private $_vars=array();
private $_file;
public function __construct($file)
{
$this->_file='views/'.$file.'.php';
}
public function set($var, $value=null)
{
if (is_array($var))
{
$this->_vars=array_merge($var, $this->_vars);
}
else
$this->_vars[$var]=$value;
return $this;
}
public function output()
{
if (count($this->_vars))
extract($this->_vars, EXTR_REFS);
require($this->_file);
exit;
}
public static function factory($file)
{
return new self($file);
}
}
test.php (top level view)
<html>
<body>
Hey <?=$name?>! This is <?=$adj?>!
<?=View::factory('embed')->output()?>
</body>
</html>
embed.php (embedded in test.php
<html>
<body>
Hey <?=$name?>! This is an embedded view file!!
</body>
</html>
Code:
$vars=array(
'name' => 'ryan',
'adj' => 'cool'
);
View::factory('test')->set($vars)->output();
Output:
Hey ryan! This is cool! Hey [error for $name not being defined]
this is an embedded view file!!
The problem is the variables I set in the top level view do not get passed to the embedded view. How could I make that happen?
So, I'm not exactly answering your question, but here's my super-simple hand-grown template system. It supports what you're trying to do, although the interface is different.
// Usage
$main = new SimpleTemplate("templating/html.php");
$main->extract($someObject);
$main->extract($someArray);
$main->name = "my name";
$subTemplate = new SimpleTemplate("templating/another.php");
$subTemplate->parent($main);
$main->placeholderForAnotherTemplate = $subTemplate->run();
echo $main; // or $main->run();
// html.php
<html><body><h1>Title <?= $name ?></h1><p><?= $placeHolderForAnotherTemplate ?></p></body></html>
<?php
// SimpleTemplate.php
function object_to_array($object)
{
$array = array();
foreach($object as $property => $value)
{
$array[$property] = $value;
}
return $array;
}
class SimpleTemplate
{
public $source;
public $path;
public $result;
public $parent;
public function SimpleTemplate($path=false, $source=false)
{
$this->source = array();
$this->extract($source);
$this->path($path);
}
public function __toString()
{
return $this->run();
}
public function extract($source)
{
if ($source)
{
foreach ($source as $property => $value)
{
$this->source[$property] = $value;
}
}
}
public function parent($parent)
{
$this->parent = $parent;
}
public function path($path)
{
$this->path = $path;
}
public function __set($name, $value)
{
$this->source[$name] = $value;
}
public function __get($name)
{
return isset($this->source[$name]) ? $this->source[$name] : "";
}
public function mergeSource()
{
if (isset($this->parent))
return array_merge($this->parent->mergeSource(), $this->source);
else
return $this->source;
}
public function run()
{
ob_start();
extract ($this->mergeSource());
include $this->path;
$this->result = ob_get_contents();
ob_end_clean();
return $this->result;
}
}
well, you create a new instance of the class, so there are no variables defined in the embedded template. you should try to copy the object, rather than creating a new one.
edit: I'm talking about the factory method
The main issue is that your views have no direct knowledge of each other. By calling this:
<?=View::factory('embed')->output()?>
in your "parent" view, you create and output a template that has no knowledge of the fact that it is inside another template.
There are two approaches I could recommend here.
#1 - Associate your templates.
By making your embedded templates "children" of a parent template, you could allow them to have access to the parent's variables at output() time. I utilize this approach in a View system I built. It goes something like this:
$pView = new View_Parent_Class();
$cView = new View_Child_Class();
$pView->addView($cView);
At $pview->render() time, the child view is easily given access to the parent's variables.
This method might require a lot of refactoring for you, so I'll leave out the dirty details, and go into the second approach.
#2 - Pass the parent variables
This would probably be the easiest method to implement given the approach you've taken so far. Add an optional parameter to your output method, and rewrite it slightly, like this:
public function output($extra_vars = null)
{
if (count($this->_vars))
extract($this->_vars, EXTR_REFS);
if (is_array($extra_vars)) extract($extra_vars, EXTR_REFS);
require($this->_file);
exit;
}
If you add a simple getter method as well:
public function get_vars()
{
return $this->_vars;
}
Then you can embed your files with what is effectively read-access to the parent's variables:
<?=View::factory('embed')->output($this->get_vars())?>
$this will be a reference to the current template, ie. the parent. Note that you can have variable name collisions via this method because of the two extract calls.
You could make your $_vars property static, not particularly elegant, but would work for what you are trying to achieve.
On a side note... your array_merge() in the set() function is wrong, swap your 2 variables around.