TUTORIAL: Completamente funcional simple motor de plantillas (cont.)
- Bogey
- Bogey


- Registrado: Jul 14, 2005
- Mensajes: 8211
- Loc: USA
- Status: Offline
Introducción
Este tutorial se extiende en el tutorial anterior de la Totalmente funcional motor de plantilla simple . Habría algunas funciones de edición y finalmente se le proporcionará la capacidad de almacenamiento en caché de aquí.
Antes de empezar en esto, que me confiese...la clase de almacenamiento en caché estoy a punto de desatar no está escrito por mí...Lo encontré en algún lugar aquí en Ozzu y asumió que estaba bien para mí utilizar...ya que funciona igual que lo necesito, yo no se encontró ninguna necesidad de mí recodificar otro, a pesar de que podía (lo prometo...Realmente puedo gif "alt =": lol: "title =" Laughing "> )
Este tutorial no es, por cualquier medio, el último tutorial sobre la base de esta completamente funcional simple plantilla de motor...cuando hago lo suficiente las modificaciones en la clase para llenar una página con grandes cambios y si te enseña algo...entonces la enfermedad después de otro aquí...pero podría ser el último gif "alt =": lol: "title =" Laughing ">
Añadido
Vamos a empezar por añadir algunas funciones más aquí: La función se llama include_file .
PHP Código: [ Select ]
<?php
function include_file($file)
{
}
?>
function include_file($file)
{
}
?>
- <?php
- function include_file($file)
- {
- }
- ?>
La razón para ello es que a veces se quiere poner un nombre de archivo que se establece en una variable, pero que no desea incluir en realidad el contenido del mismo en la plantilla...así que hice una solución simple aquí...para todos los archivos que Usted no quiere incluir en el archivo, basta con añadir un * delante de él...el * es perfecto porque no está permitido en el nombre del archivo que se fijará cuando se crea un archivo y que nos permite crear esta funcionalidad
PHP Código: [ Select ]
<?php
function include_file($file)
{
// Taking the first character from the filename
$find = substr($file, 0, 1);
// Checking if * exists in $filename
if($find != '*')
{
return true;
}
return false;
}
?>
function include_file($file)
{
// Taking the first character from the filename
$find = substr($file, 0, 1);
// Checking if * exists in $filename
if($find != '*')
{
return true;
}
return false;
}
?>
- <?php
- function include_file($file)
- {
- // Taking the first character from the filename
- $find = substr($file, 0, 1);
- // Checking if * exists in $filename
- if($find != '*')
- {
- return true;
- }
- return false;
- }
- ?>
PHP Código: [ Select ]
<?php
function include_file($file)
{
// Checking if * exists in $filename
if(strpos($file, '*') != false)
{
return true;
}
return false;
}
?>
function include_file($file)
{
// Checking if * exists in $filename
if(strpos($file, '*') != false)
{
return true;
}
return false;
}
?>
- <?php
- function include_file($file)
- {
- // Checking if * exists in $filename
- if(strpos($file, '*') != false)
- {
- return true;
- }
- return false;
- }
- ?>
La siguiente función es lo que he llamado a ser unclude_file . Por lo general, hace lo que hace la función anterior, pero también quita el asterisco para el saneamiento.
PHP Código: [ Select ]
<?php
function unclude_file($file, $perform = false)
{
// Checking if the file was passed as an un-includeable
if($this->include_file($file) === false)
{
// Checking if we should actually remove the first character (It being the '*')
if($perform == true)
{
// Counting the number of letters $file consists of
$ltrs = strlen($file);
// Returning the trimmed $file
return substr($file, 1, $ltrs);
}
return true;
}
return false;
}
?>
function unclude_file($file, $perform = false)
{
// Checking if the file was passed as an un-includeable
if($this->include_file($file) === false)
{
// Checking if we should actually remove the first character (It being the '*')
if($perform == true)
{
// Counting the number of letters $file consists of
$ltrs = strlen($file);
// Returning the trimmed $file
return substr($file, 1, $ltrs);
}
return true;
}
return false;
}
?>
- <?php
- function unclude_file($file, $perform = false)
- {
- // Checking if the file was passed as an un-includeable
- if($this->include_file($file) === false)
- {
- // Checking if we should actually remove the first character (It being the '*')
- if($perform == true)
- {
- // Counting the number of letters $file consists of
- $ltrs = strlen($file);
- // Returning the trimmed $file
- return substr($file, 1, $ltrs);
- }
- return true;
- }
- return false;
- }
- ?>
Además, puedo añadir una variable a toda la clase llamada include_files . Contiene cierto si desea que los archivos que se pasan en la definición de variables. que se incluirán en la plantilla (igual que en su contenido) o no incluidos en las plantillas (Los nombres de los archivos que se incluirán...no la fuente).
PHP Código: [ Select ]
<?php
class tpl {
// Various variables used throughout the class
public $vari, $template, $page, [color=#0000FF]$vstart, $vend, $include_files;
}
?>
class tpl {
// Various variables used throughout the class
public $vari, $template, $page, [color=#0000FF]$vstart, $vend, $include_files;
}
?>
- <?php
- class tpl {
- // Various variables used throughout the class
- public $vari, $template, $page, [color=#0000FF]$vstart, $vend, $include_files;
- }
- ?>
Editado
Derecho, le dije que ha editado algunas funciones, por lo que permite obtener en él gif "alt = =":)" título" Smile ">
La primera función que se ha editado el svariable para dar cabida a la include_file () función y el unclude_file () función. Aquí está en todo su esplendor
PHP Código: [ Select ]
<?php
function svariable($return = false)
{
// Converting set variables to the text defined in the parent PHP file
foreach($this->vari as $key => $value)
{
// Checking if the value is a file and if it exists if it is a file
if(is_file($value) && file_exists($value))
{
if($this->include_files === true && ($this->include_file($value) === true))
{
// Getting the contents of the file
$value = file_get_contents($value);
// Replacing the KEY variable with the contents of the file
$this->text = str_replace($this->vstart . $key . $this->vend, $value, $this->text);
}
else
{
// Replacing the KEY variable with the value
$this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
}
}
else
{
if($this->unclude_file($value) === true)
{
$value = $this->unclude_file($value, true);
}
// Replacing the KEY variable with the value
$this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
}
}
// Checking if we need to return the result
if($return)
{
return $this->text;
}
}
?>
function svariable($return = false)
{
// Converting set variables to the text defined in the parent PHP file
foreach($this->vari as $key => $value)
{
// Checking if the value is a file and if it exists if it is a file
if(is_file($value) && file_exists($value))
{
if($this->include_files === true && ($this->include_file($value) === true))
{
// Getting the contents of the file
$value = file_get_contents($value);
// Replacing the KEY variable with the contents of the file
$this->text = str_replace($this->vstart . $key . $this->vend, $value, $this->text);
}
else
{
// Replacing the KEY variable with the value
$this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
}
}
else
{
if($this->unclude_file($value) === true)
{
$value = $this->unclude_file($value, true);
}
// Replacing the KEY variable with the value
$this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
}
}
// Checking if we need to return the result
if($return)
{
return $this->text;
}
}
?>
- <?php
- function svariable($return = false)
- {
- // Converting set variables to the text defined in the parent PHP file
- foreach($this->vari as $key => $value)
- {
- // Checking if the value is a file and if it exists if it is a file
- if(is_file($value) && file_exists($value))
- {
- if($this->include_files === true && ($this->include_file($value) === true))
- {
- // Getting the contents of the file
- $value = file_get_contents($value);
- // Replacing the KEY variable with the contents of the file
- $this->text = str_replace($this->vstart . $key . $this->vend, $value, $this->text);
- }
- else
- {
- // Replacing the KEY variable with the value
- $this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
- }
- }
- else
- {
- if($this->unclude_file($value) === true)
- {
- $value = $this->unclude_file($value, true);
- }
- // Replacing the KEY variable with the value
- $this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
- }
- }
- // Checking if we need to return the result
- if($return)
- {
- return $this->text;
- }
- }
- ?>
El caché
Bien, desde que asumí esta clase de alguien en este foro, la enfermedad sólo después de toda la clase entera aquí (sin colorear de rojo...Tengo que cada línea de color por separado...).
Lo que hace, sin embargo, se crea un archivo con las variables no sustituye...que incluye todos los archivos y luego lo almacena en caché. El identificador (o el nombre que se ahorraría a) es el nombre del archivo...por lo que si está utilizando una plantilla de más de una vez en diferentes archivos de PHP...no caché que
PHP Código: [ Select ]
<?php
class fcache {
var $name = NULL; // private members only >= PHP 5
var $value = array();
var $ttl;
function __construct($name, $ttl = 3600) { // Default $ttl is 3600 (60 minutes until expiry)
$this->name = $name;
$this->ttl = $ttl;
}
function check() {
$cached = false;
$file_name = './cache/' . $this->name . ".cache";
if(file_exists($file_name))
{
$modified = filemtime($file_name);
if(time() - $this->ttl < $modified)
{
$fp = fopen($file_name, "rt");
if($fp)
{
$temp_value = fread($fp, filesize($file_name));
fclose($fp);
$this->value = unserialize($temp_value);
$cached = true;
}
}
else
{
$this->del_value($this->name);
$this->set_value($this->name, $this->value);
$this->save();
}
}
return $cached;
}
function save() {
$file_name = './cache/' . $this->name . ".cache";
$fp = fopen($file_name, "wt");
if($fp)
{
fwrite($fp, serialize($this->value));
fclose($fp);
}
}
function set_value($key, $value) {
$this->value[$key] = $value;
}
function get_value($key) {
if(isset($this->value[$key]))
{
return $this->value[$key];
}
else
{
return null;
}
}
function del_value($key)
{
$file_name = './cache/' . $this->name . ".cache";
if(file_exists($file_name))
{
unset($this->value[$key]);
return unlink($file_name);
}
return false;
}
}
?>
class fcache {
var $name = NULL; // private members only >= PHP 5
var $value = array();
var $ttl;
function __construct($name, $ttl = 3600) { // Default $ttl is 3600 (60 minutes until expiry)
$this->name = $name;
$this->ttl = $ttl;
}
function check() {
$cached = false;
$file_name = './cache/' . $this->name . ".cache";
if(file_exists($file_name))
{
$modified = filemtime($file_name);
if(time() - $this->ttl < $modified)
{
$fp = fopen($file_name, "rt");
if($fp)
{
$temp_value = fread($fp, filesize($file_name));
fclose($fp);
$this->value = unserialize($temp_value);
$cached = true;
}
}
else
{
$this->del_value($this->name);
$this->set_value($this->name, $this->value);
$this->save();
}
}
return $cached;
}
function save() {
$file_name = './cache/' . $this->name . ".cache";
$fp = fopen($file_name, "wt");
if($fp)
{
fwrite($fp, serialize($this->value));
fclose($fp);
}
}
function set_value($key, $value) {
$this->value[$key] = $value;
}
function get_value($key) {
if(isset($this->value[$key]))
{
return $this->value[$key];
}
else
{
return null;
}
}
function del_value($key)
{
$file_name = './cache/' . $this->name . ".cache";
if(file_exists($file_name))
{
unset($this->value[$key]);
return unlink($file_name);
}
return false;
}
}
?>
- <?php
- class fcache {
- var $name = NULL; // private members only >= PHP 5
- var $value = array();
- var $ttl;
- function __construct($name, $ttl = 3600) { // Default $ttl is 3600 (60 minutes until expiry)
- $this->name = $name;
- $this->ttl = $ttl;
- }
- function check() {
- $cached = false;
- $file_name = './cache/' . $this->name . ".cache";
- if(file_exists($file_name))
- {
- $modified = filemtime($file_name);
- if(time() - $this->ttl < $modified)
- {
- $fp = fopen($file_name, "rt");
- if($fp)
- {
- $temp_value = fread($fp, filesize($file_name));
- fclose($fp);
- $this->value = unserialize($temp_value);
- $cached = true;
- }
- }
- else
- {
- $this->del_value($this->name);
- $this->set_value($this->name, $this->value);
- $this->save();
- }
- }
- return $cached;
- }
- function save() {
- $file_name = './cache/' . $this->name . ".cache";
- $fp = fopen($file_name, "wt");
- if($fp)
- {
- fwrite($fp, serialize($this->value));
- fclose($fp);
- }
- }
- function set_value($key, $value) {
- $this->value[$key] = $value;
- }
- function get_value($key) {
- if(isset($this->value[$key]))
- {
- return $this->value[$key];
- }
- else
- {
- return null;
- }
- }
- function del_value($key)
- {
- $file_name = './cache/' . $this->name . ".cache";
- if(file_exists($file_name))
- {
- unset($this->value[$key]);
- return unlink($file_name);
- }
- return false;
- }
- }
- ?>
Ahora tenemos que poner eso en nuestra gentemp .
PHP Código: [ Select ]
<?php
function gentemp($cache = false, $return = false)
{
// Converting simple function variables to function
$this->sfvariable();
// Checking if the page needs to be cached... if so, cache it.
if($cache)
{
// Setting the cache class object
$cache = new fcache($this->page);
// Checking if the cache is available for the current page
if($cache->check())
{
// Retrieving the cached contents of the page
$this->text = $cache->get_value($this->page);
}
else
{
// Setting the cache with the contents of the current page
$cache->set_value($cache->name, $this->text);
// Saving the cache
$cache->save();
// Retrieving the cached contents of the page
$this->text = $cache->get_value($this->page);
}
}
// Converting simple variables to variables
$this->svariable();
// Checking if we need to echo or return the page
if($return)
{
// Returning the page
return $this->text;
}
else
{
// Echoing the page
echo $this->text;
}
}
?>
function gentemp($cache = false, $return = false)
{
// Converting simple function variables to function
$this->sfvariable();
// Checking if the page needs to be cached... if so, cache it.
if($cache)
{
// Setting the cache class object
$cache = new fcache($this->page);
// Checking if the cache is available for the current page
if($cache->check())
{
// Retrieving the cached contents of the page
$this->text = $cache->get_value($this->page);
}
else
{
// Setting the cache with the contents of the current page
$cache->set_value($cache->name, $this->text);
// Saving the cache
$cache->save();
// Retrieving the cached contents of the page
$this->text = $cache->get_value($this->page);
}
}
// Converting simple variables to variables
$this->svariable();
// Checking if we need to echo or return the page
if($return)
{
// Returning the page
return $this->text;
}
else
{
// Echoing the page
echo $this->text;
}
}
?>
- <?php
- function gentemp($cache = false, $return = false)
- {
- // Converting simple function variables to function
- $this->sfvariable();
- // Checking if the page needs to be cached... if so, cache it.
- if($cache)
- {
- // Setting the cache class object
- $cache = new fcache($this->page);
- // Checking if the cache is available for the current page
- if($cache->check())
- {
- // Retrieving the cached contents of the page
- $this->text = $cache->get_value($this->page);
- }
- else
- {
- // Setting the cache with the contents of the current page
- $cache->set_value($cache->name, $this->text);
- // Saving the cache
- $cache->save();
- // Retrieving the cached contents of the page
- $this->text = $cache->get_value($this->page);
- }
- }
- // Converting simple variables to variables
- $this->svariable();
- // Checking if we need to echo or return the page
- if($return)
- {
- // Returning the page
- return $this->text;
- }
- else
- {
- // Echoing the page
- echo $this->text;
- }
- }
- ?>
Ejemplo de uso
Ahora, un ejemplo de uso de todo esto estaría en la primera parte de este tutorial ( ??? ) O por debajo
proceso. php
PHP Código: [ Select ]
<?php
require('includes/globals.php');
$db->connect();
$db->last_sql = $db->build_query(array('*', 'forum_a'));
$result = $db->last_sql_data(false, 'SQL Results Data', true);
$db->close();
$tpl->template = 'default';
$tpl->page = 'index';
$tpl->start();
include('includes/global_vars.php');
$tpl->vari = array_merge($tpl->vari, array(
'SQL_QUERY' => $result,
'MEMBER_STUFF' => ((isset($_SESSION['uid'])) ? 'members.html' : 'non_members.html'),
'USERNAME' => $username,
'LAST_VISIT' => date(MM/DD/YYYY hh:mm:ss, $last_visit)
'NOW_DATE' => date(MM/DD/YYYY hh:mm:ss)
));
$tpl->gentemp(true);
?>
require('includes/globals.php');
$db->connect();
$db->last_sql = $db->build_query(array('*', 'forum_a'));
$result = $db->last_sql_data(false, 'SQL Results Data', true);
$db->close();
$tpl->template = 'default';
$tpl->page = 'index';
$tpl->start();
include('includes/global_vars.php');
$tpl->vari = array_merge($tpl->vari, array(
'SQL_QUERY' => $result,
'MEMBER_STUFF' => ((isset($_SESSION['uid'])) ? 'members.html' : 'non_members.html'),
'USERNAME' => $username,
'LAST_VISIT' => date(MM/DD/YYYY hh:mm:ss, $last_visit)
'NOW_DATE' => date(MM/DD/YYYY hh:mm:ss)
));
$tpl->gentemp(true);
?>
- <?php
- require('includes/globals.php');
- $db->connect();
- $db->last_sql = $db->build_query(array('*', 'forum_a'));
- $result = $db->last_sql_data(false, 'SQL Results Data', true);
- $db->close();
- $tpl->template = 'default';
- $tpl->page = 'index';
- $tpl->start();
- include('includes/global_vars.php');
- $tpl->vari = array_merge($tpl->vari, array(
- 'SQL_QUERY' => $result,
- 'MEMBER_STUFF' => ((isset($_SESSION['uid'])) ? 'members.html' : 'non_members.html'),
- 'USERNAME' => $username,
- 'LAST_VISIT' => date(MM/DD/YYYY hh:mm:ss, $last_visit)
- 'NOW_DATE' => date(MM/DD/YYYY hh:mm:ss)
- ));
- $tpl->gentemp(true);
- ?>
Que cierto en el gentemp ( en el trozo de código anterior indica que el código de caché también.
Y el archivo de plantilla podría parecer
HTML Código: [ Select ]
<!-- INCLUDE header.html -->
<div id="content">
<h6 id="header">Welcome {USERNAME} your last visit was {LAST_VISIT} from today ({NOW)DATE})</h6>
<p>{MEMBER_STUFF}</p>
<p>{SQL_QUERY}</p>
</div>
<!-- INCLUDE footer.html -->
<div id="content">
<h6 id="header">Welcome {USERNAME} your last visit was {LAST_VISIT} from today ({NOW)DATE})</h6>
<p>{MEMBER_STUFF}</p>
<p>{SQL_QUERY}</p>
</div>
<!-- INCLUDE footer.html -->
- <!-- INCLUDE header.html -->
- <div id="content">
- <h6 id="header">Welcome {USERNAME} your last visit was {LAST_VISIT} from today ({NOW)DATE})</h6>
- <p>{MEMBER_STUFF}</p>
- <p>{SQL_QUERY}</p>
- </div>
- <!-- INCLUDE footer.html -->
La esperanza que tenía sentido
Conclusión
Bueno, esto es todo por ahora. Espero que te haya gustado y que encontrar un buen uso para que
Attachments:
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
- Anonymous
- Bot


- Registrado: 25 Feb 2008
- Mensajes: ?
- Loc: Ozzuland
- Status: Online
Marzo 4th, 2009, 4:58 pm
- Bogey
- Bogey


- Registrado: Jul 14, 2005
- Mensajes: 8211
- Loc: USA
- Status: Offline
El tutorial de uso que se ha Creado . Échale un vistazo para saber la utilidad de la clase. Espero que era descriptivo en...si yo no estaba, no dude en responder a la guía de aprendizaje con el uso de cualquier duda que pueda tener.
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
- Bogey
- Bogey


- Registrado: Jul 14, 2005
- Mensajes: 8211
- Loc: USA
- Status: Offline
Incluso un simple clase de plantilla fue creado por un perro rabioso con poco menos de la capacidad, la funcionalidad y la misma llegó a una forma diferente.
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
Página 1 de 1
Para responder a este tema que necesita para ingresar o registrarse. Es gratis.
Publicar Información
- Total de mensajes en este tema: 3 mensajes
- Moderador: Tutorial Writers
- Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 3 invitados
- No puede abrir nuevos temas en este Foro
- No puede responder a temas en este Foro
- No puede editar sus mensajes en este Foro
- No puede borrar sus mensajes en este Foro
- No puede enviar adjuntos en este Foro
