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

  • Bogey
  • Bogey
  • Genius
  • Avatar de Usuario
  • Registrado: Jul 14, 2005
  • Mensajes: 8211
  • Loc: USA
  • Status: Offline

Nota Marzo 4th, 2009, 4:58 pm

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)
{
 
}
?>
  1. <?php
  2. function include_file($file)
  3. {
  4.  
  5. }
  6. ?>

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;
}
?>
  1. <?php
  2. function include_file($file)
  3. {
  4.     // Taking the first character from the filename
  5.     $find = substr($file, 0, 1);
  6.    
  7.     // Checking if * exists in $filename
  8.     if($find != '*')
  9.     {
  10.         return true;
  11.     }
  12.     return false;
  13. }
  14. ?>
¿Qué hace esta función es comprobar el primer personaje del nombre de archivo prevista *. Si no te gusta este método, puede sustituir la función con el siguiente. < Br>
PHP Código: [ Select ]
<?php
function include_file($file)
{
    // Checking if * exists in $filename
    if(strpos($file, '*') != false)
    {
        return true;
    }
    return false;
}
?>
  1. <?php
  2. function include_file($file)
  3. {
  4.     // Checking if * exists in $filename
  5.     if(strpos($file, '*') != false)
  6.     {
  7.         return true;
  8.     }
  9.     return false;
  10. }
  11. ?>
De esta forma es utilizando una menor cantidad de código, pero esta vez, usted puede poner el asterisco * en cualquier parte del nombre de archivo...su no se limitan a estar en el frente.

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;
}
?>
  1. <?php
  2. function unclude_file($file, $perform = false)
  3. {
  4.     // Checking if the file was passed as an un-includeable
  5.     if($this->include_file($file) === false)
  6.     {
  7.         // Checking if we should actually remove the first character (It being the '*')
  8.         if($perform == true)
  9.         {
  10.             // Counting the number of letters $file consists of
  11.             $ltrs = strlen($file);
  12.            
  13.             // Returning the trimmed $file
  14.             return substr($file, 1, $ltrs);
  15.         }
  16.         return true;
  17.     }
  18.     return false;
  19. }
  20. ?>
Creo que se puede poner todo esto en una función si realmente creo en ello, pero la enfermedad lo rompen en la...¿por qué? Porque soy demasiado perezoso para editar este tutorial para acomodar el cambio :roll: gif "alt =": lol: "title =" Laughing ">

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;
 
}
?>
  1. <?php
  2. class tpl {
  3.  
  4.     // Various variables used throughout the class
  5.     public $vari, $template, $page, [color=#0000FF]$vstart, $vend, $include_files;
  6.  
  7. }
  8. ?>
Las variables de color azul es lo que acabo de cargar en que para que sea más correcto (?). Me las puso en la función inicio y utilizarlos en unas pocas funciones...en la clase

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 :D

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;
    }
}
?>
  1. <?php
  2. function svariable($return = false)
  3. {
  4.     // Converting set variables to the text defined in the parent PHP file
  5.     foreach($this->vari as $key => $value)
  6.     {
  7.         // Checking if the value is a file and if it exists if it is a file
  8.         if(is_file($value) && file_exists($value))
  9.         {
  10.             if($this->include_files === true  && ($this->include_file($value) === true))
  11.             {
  12.                 // Getting the contents of the file
  13.                 $value = file_get_contents($value);
  14.                
  15.                 // Replacing the KEY variable with the contents of the file
  16.                 $this->text = str_replace($this->vstart . $key . $this->vend, $value, $this->text);
  17.             }
  18.             else
  19.             {
  20.                 // Replacing the KEY variable with the value
  21.                 $this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
  22.             }
  23.         }
  24.         else
  25.         {
  26.             if($this->unclude_file($value) === true)
  27.             {
  28.                 $value = $this->unclude_file($value, true);
  29.             }
  30.            
  31.             // Replacing the KEY variable with the value
  32.             $this->text = str_replace($this->vstart . $key . $this->vend, $value,$this->text);
  33.         }
  34.     }
  35.    
  36.     // Checking if we need to return the result
  37.     if($return)
  38.     {
  39.         return $this->text;
  40.     }
  41. }
  42. ?>
Eso es todo por esta gif "alt = =":)" título" Smile ">

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 :D De lo contrario, se hace un lío para arriba.
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;
    }
}
?>
  1. <?php
  2. class fcache {
  3.     var $name = NULL; // private members only >= PHP 5
  4.     var $value = array();
  5.     var $ttl;
  6.  
  7.     function __construct($name, $ttl = 3600) { // Default $ttl is 3600 (60 minutes until expiry)
  8.         $this->name = $name;
  9.         $this->ttl = $ttl;
  10.     }
  11.  
  12.     function check() {
  13.         $cached = false;
  14.         $file_name = './cache/' . $this->name . ".cache";
  15.         if(file_exists($file_name))
  16.         {
  17.             $modified = filemtime($file_name);
  18.             if(time() - $this->ttl < $modified)
  19.             {
  20.                 $fp = fopen($file_name, "rt");
  21.                 if($fp)
  22.                 {
  23.                     $temp_value = fread($fp, filesize($file_name));
  24.                     fclose($fp);
  25.                     $this->value = unserialize($temp_value);
  26.                     $cached = true;
  27.                 }
  28.             }
  29.             else
  30.             {
  31.                 $this->del_value($this->name);
  32.                 $this->set_value($this->name, $this->value);
  33.                 $this->save();
  34.             }
  35.         }
  36.         return $cached;
  37.     }
  38.  
  39.     function save() {
  40.         $file_name = './cache/' . $this->name . ".cache";
  41.         $fp = fopen($file_name, "wt");
  42.         if($fp)
  43.         {
  44.             fwrite($fp, serialize($this->value));
  45.             fclose($fp);
  46.         }
  47.     }
  48.  
  49.     function set_value($key, $value) {
  50.         $this->value[$key] = $value;
  51.     }
  52.  
  53.     function get_value($key) {
  54.         if(isset($this->value[$key]))
  55.         {
  56.             return $this->value[$key];
  57.         }
  58.         else
  59.         {
  60.             return null;
  61.         }
  62.     }
  63.  
  64.     function del_value($key)
  65.     {
  66.         $file_name = './cache/' . $this->name . ".cache";
  67.         if(file_exists($file_name))
  68.         {
  69.             unset($this->value[$key]);
  70.             return unlink($file_name);
  71.         }
  72.         return false;
  73.     }
  74. }
  75. ?>

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;
    }
}
?>
  1. <?php
  2. function gentemp($cache = false, $return = false)
  3. {
  4.     // Converting simple function variables to function
  5.     $this->sfvariable();
  6.  
  7.     // Checking if the page needs to be cached... if so, cache it.
  8.     if($cache)
  9.     {
  10.         // Setting the cache class object
  11.         $cache = new fcache($this->page);
  12.        
  13.         // Checking if the cache is available for the current page
  14.         if($cache->check())
  15.         {
  16.             // Retrieving the cached contents of the page
  17.             $this->text = $cache->get_value($this->page);
  18.         }
  19.         else
  20.         {
  21.             // Setting the cache with the contents of the current page
  22.             $cache->set_value($cache->name, $this->text);
  23.            
  24.             // Saving the cache
  25.             $cache->save();
  26.            
  27.             // Retrieving the cached contents of the page
  28.             $this->text = $cache->get_value($this->page);
  29.         }
  30.     }
  31.  
  32.     // Converting simple variables to variables
  33.     $this->svariable();
  34.    
  35.     // Checking if we need to echo or return the page
  36.     if($return)
  37.     {
  38.         // Returning the page
  39.         return $this->text;
  40.     }
  41.     else
  42.     {
  43.         // Echoing the page
  44.         echo $this->text;
  45.     }
  46. }
  47. ?>


Ejemplo de uso


Ahora, un ejemplo de uso de todo esto estaría en la primera parte de este tutorial ( ??? ) O por debajo :P

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);
?>
  1. <?php
  2. require('includes/globals.php');
  3.  
  4. $db->connect();
  5. $db->last_sql = $db->build_query(array('*', 'forum_a'));
  6. $result = $db->last_sql_data(false, 'SQL Results Data', true);
  7. $db->close();
  8.  
  9. $tpl->template = 'default';
  10. $tpl->page = 'index';
  11. $tpl->start();
  12.  
  13. include('includes/global_vars.php');
  14.  
  15. $tpl->vari = array_merge($tpl->vari, array(
  16.     'SQL_QUERY' => $result,
  17.     'MEMBER_STUFF' => ((isset($_SESSION['uid'])) ? 'members.html' : 'non_members.html'),
  18.     'USERNAME' => $username,
  19.     'LAST_VISIT' => date(MM/DD/YYYY hh:mm:ss, $last_visit)
  20.     'NOW_DATE' => date(MM/DD/YYYY hh:mm:ss)
  21. ));
  22.  
  23. $tpl->gentemp(true);
  24. ?>

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 -->
  1. <!-- INCLUDE header.html -->
  2. <div id="content">
  3.      <h6 id="header">Welcome {USERNAME} your last visit was {LAST_VISIT} from today ({NOW)DATE})</h6>
  4.      <p>{MEMBER_STUFF}</p>
  5.      <p>{SQL_QUERY}</p>
  6. </div>
  7. <!-- INCLUDE footer.html -->

La esperanza que tenía sentido :D

Conclusión


Bueno, esto es todo por ahora. Espero que te haya gustado y que encontrar un buen uso para que :D

Attachments:
template.zip

(2.89 KiB) 477 veces

The Template Engine Source Code

"Bring forth therefore fruits meet for repentance:" Matthew 3:8
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Marzo 4th, 2009, 4:58 pm

  • Bogey
  • Bogey
  • Genius
  • Avatar de Usuario
  • Registrado: Jul 14, 2005
  • Mensajes: 8211
  • Loc: USA
  • Status: Offline

Nota Marzo 6th, 2009, 2:51 pm

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
  • Genius
  • Avatar de Usuario
  • Registrado: Jul 14, 2005
  • Mensajes: 8211
  • Loc: USA
  • Status: Offline

Nota Julio 1st, 2009, 12:10 am

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

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
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC