Visualizzazione risultati 1 fino 19 di 19

Discussione: Creare sito con tpl e php, sistema template simile a phpbb

  1. #1
    Guest

    Predefinito Creare sito con tpl e php, sistema template simile a phpbb

    Il titolo credo dica tutto.

    Però lo voglio spiegare meglio anche per chi leggerà questo thread.

    Allora, vorrei migliorare il sistema template che già utilizzo (ho postato una parte del mio sito in un thread ieri, ma mi viene sempre difficile gestire il tutto, quindi ho pensato di poter fare un sistema simile a phpbb per la gestione delle variabili del template.

    Mi sono spulciato il codice ma non ci ho capito molto, togliendo le funzioni create per l'assegnazione dei valori.

    Ora, chiedo a voi, se potreste aiutarmi a utilizzare un sistema simile, cioè, supponiamo di avere un file index.php con:

    Codice PHP:
    //Assegno il .tpl della pagina
    $var->funct_assign_tpl(array(
    'name' => 'file.tpl'
    ));


    //Definisco le variabili da utilizzare nel .tpl con {VAR}
    $var->funct_assign_vars(array(
    'VAR_TEMPL' => 'Valore di Var Templ',
    ));
    //Nel .tpl richiamerò il valore con {VAR_TEMPLE}

    $var->funct_start_tpl('name'); //esegue il .tpl assegnato in precedenza
    Ho fatto tutto generale, cioè, funct_assign_vars sarà la funzione che assegnerà le variabili, funct_start_tpl sarà quella che esguirà il tpl assegnato, mentre funct_assign_tpl sarà quella che assegnerà il .tpl da eseguire succerssivamente.

    Fino ad ora utilizzo la funzione eval() direttamente nella pagina ma non posso fare tutto automaticamente, insomma, non sono soddisfatto.

    Per favore, non ditemi di usare Smarty o simili, vorrei solo imparare a fare una cosa simile a phpbb

  2. #2
    Guest

    Predefinito

    Ragazzi, tiro su la discussione. Allora, girando un pò in internet ho trovato una risorsa che ha estrapolato il sistema template di phpbb2, proprio quello che cercavo.

    Lo potete trovare qui: http://biccheddu.altervista.org/template.class.txt

    Però ho un problema.

    Quando vado a fare una pagina di esempio:
    Codice PHP:
    <?php
    include('includes/template.class.php' );

    $template = new Template();
    $template->set_rootdir = './templates/';

    $template->set_filenames(array('body' => 'index.tpl'));

    $template->make_filename('body');
    $template->compile('body');
    $template->loadfile('body');

    $template->assign_vars(array(
    'ERROR_MESSAGE' => 'Error Message',
    )
    );

    $template->pparse('body');
    ?>
    Mi viene restituito:
    Codice:
    Fatal error: Call to private method Template::make_filename() from context '' in \example.php on line 9
    Da cosa può dipendere il problema??

    Scusate ma di programmazione ad oggetti non ne ho mai fatta, sto iniziando da poco

  3. #3
    Guest

    Predefinito

    che hai tentato una chiamata ad un metodo (make_filename) che è definito privato, cioè che puoi richiamarlo solo dall'interno della stessa classe (Template)
    Ultima modifica di Inverno : 16-05-2009 alle ore 18.23.09

  4. #4
    Guest

    Predefinito

    Ho provato così:
    Codice PHP:
    <?php
    include('includes/template.class.php' );

    $template = new Template();
    $template->set_rootdir = './templates/';

    $template->set_filenames(array('body' => 'index.tpl'));

    #$template->make_filename('body');
    $template->compile('body');
    #$template->loadfile('body');

    $template->assign_vars(array(
    'ERROR_MESSAGE' => 'Error Message',
    )
    );

    $template->pparse('body');
    ?>
    E mi restituisce:
    Codice:
    Template->make_filename(): Error - file does not exist
    
    Warning: implode() [function.implode]: Invalid arguments passed in \includes\template.class.php on line 213
    Template->loadfile(): File for handle body is empty
    Se provo cosìa decommentare $template->loadfile('body'); mi mostra:
    Codice:
    Template->make_filename(): Error - file does not exist
    
    Fatal error: Call to private method Template::loadfile() from context '' in E:\xampp\htdocs\new_fb\index.php on line 11
    Come diavolo devo usare questa classe per usare il template engine?

  5. #5
    Guest

    Predefinito

    loadfile non lo puoi chiamare.. è privato!

    #edit comunque io ho provato il codice e mi funziona... forse è un problema di directory, dai messaggi sembra che non trova il file che hai creato (index.tpl) ...
    Ultima modifica di stoner : 16-05-2009 alle ore 18.47.14

  6. #6
    Guest

    Predefinito

    Allora, ho rifatto un po il tutto, ora ho la root strutturata in questo modo:
    Codice:
    |-/inc/
      |-template.class.php
    |-/tpl/
      |-/cache/
      |-index.tpl
    |-index.php
    In index.php ho:
    Codice PHP:
    <?php
    include('./inc/template.class.php' );

    $template = new Template();
    $template->set_rootdir = './tpl/';

    $template->set_filenames(array('body' => 'index.tpl'));

    $template->make_filename('body');
    $template->compile('body');
    $template->loadfile('body');

    $template->assign_vars(array(
    'ERROR_MESSAGE' => 'Error Message',
    )
    );

    $template->pparse('body');
    ?>
    Mentre in /inc/template.class.php ho cambiato in questo modo le var:
    Codice PHP:
    private $_tpldata = array();
    public
    $files = array();
    public
    $root = './tpl/';
    private
    $compiled_code = array();
    private
    $uncompiled_code = array();
    private
    $use_cache = true;
    private
    $cache_directory = './tpl/cache/';
    Ho provato anche a lasciare vuote public $root e private $cache_directory ma nulla!

    Come devo fare per utilizzarlo? Non riesco a capire il problema

  7. #7
    Guest

    Predefinito

    posta template.class.php

  8. #8
    Guest

    Predefinito

    E' quello linkato qualche post più su con quella variabili modificate che ho postato.

  9. #9
    Guest

    Predefinito

    1) non me lo apre
    2) meglio che lo posti qui, che c'è il syntax highlight ;)

  10. #10
    Guest

    Predefinito

    Credo che non glie lo permetta di postarlo qui perchè supera i caratteri consentiti per post.
    @biccheddu: Per il syntax highlight puoi utilizzare highlight_string

  11. #11
    Guest

    Predefinito

    Codice PHP:
    class Template{
    private
    $_tpldata = array();
    public
    $files = array();
    public
    $root = '';
    private
    $compiled_code = array();
    private
    $uncompiled_code = array();
    private
    $use_cache = true;
    private
    $cache_directory = '';

    function
    __construct($root = "." , $use_cache = false, $cache_directory = '')
    {
    if(
    $this->set_rootdir($root))
    {
    } else {
    print(
    'Unable to find template root directory: ' . $root);
    }
    $this->use_cache = $use_cache;
    if(
    $this->use_cache)
    {
    if(
    $cache_directory)
    {
    $this->cache_directory = $cache_directory;
    } else {
    $this->cache_directory = $this->root . '/cache';
    }
    }
    }

    function
    __destruct()
    {
    $this->_tpldata = array();
    }

    public function
    set_rootdir($dir)
    {
    if(!
    is_dir($dir))
    {
    return
    false;
    }
    $this->root = $dir;
    return
    true;
    }

    public function
    set_filenames(array $filename_array)
    {
    reset($filename_array);

    foreach(
    $filename_array as $handle => $filename)
    {
    $this->files[$handle] = $this->make_filename($filename);
    }
    return
    true;
    }

    public function
    pparse($handle)
    {
    $code = '';

    if(
    $this->use_cache)
    {
    $code = $this->get_cached_code($handle);
    } else {
    if(!
    $this->loadfile($handle))
    {
    print(
    "Template->pparse(): Couldn't load template file for handle $handle");
    }
    if(!isset(
    $this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
    {
    $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);
    }
    $code = $this->compiled_code[$handle];
    }
    eval(
    $code);
    return
    true;
    }

    public function
    get_html($handle)
    {
    if(!
    $this->loadfile($handle))
    {
    print(
    "Template->assign_var_from_handle(): Couldn't load template file for handle $handle");
    }
    $_str = "";
    $code = '';

    if(
    $this->use_cache)
    {
    $code = $this->get_cached_code($handle, true, '_str');
    } else {
    $code = $this->compile($this->uncompiled_code[$handle], true, '_str');
    }
    eval(
    $code);
    return
    $_str;
    }

    public function
    assign_var_from_handle($varname, $handle)
    {
    if(!
    $this->loadfile($handle))
    {
    print(
    "Template->assign_var_from_handle(): Couldn't load template file for handle $handle");
    }

    $_str = "";
    $code = '';

    if(
    $this->use_cache)
    {
    $code = $this->get_cached_code($handle, true, '_str');
    } else {
    $code = $this->compile($this->uncompiled_code[$handle], true, '_str');
    }
    eval(
    $code);
    $this->assign_var($varname, $_str);
    return
    true;
    }

    public function
    assign_block_vars($blockname, $vararray)
    {
    if(
    strstr($blockname, '.'))
    {
    $blocks = explode('.', $blockname);
    $blockcount = sizeof($blocks) - 1;
    $str = '$this->_tpldata';
    for (
    $i = 0; $i < $blockcount; $i++)
    {
    $str .= '[\'' . $blocks[$i] . '.\']';
    eval(
    '$lastiteration = sizeof(' . $str . ') - 1;');
    $str .= '[' . $lastiteration . ']';
    }
    $str .= '[\'' . $blocks[$blockcount] . '.\'][] = $vararray;';
    eval(
    $str);
    }
    else
    {
    $this->_tpldata[$blockname . '.'][] = $vararray;
    }
    return
    true;
    }

    public function
    assign_vars($vararray)
    {
    reset ($vararray);
    while (list(
    $key, $val) = each($vararray))
    {
    $this->_tpldata['.'][0][$key] = $val;
    }
    return
    true;
    }

    public function
    assign_var($varname, $varval)
    {
    $this->_tpldata['.'][0][$varname] = $varval;
    return
    true;
    }

    private function
    make_filename($filename)
    {
    $from_http = 0;

    if(
    strtolower(substr($filename, 0 ,4)) == 'http')
    {
    $from_http = 1;
    }

    if(
    $from_http)
    {
    } else {
    if(
    substr($filename, 0, 1) != '/')
    {
    $filename = realpath($this->root . '/' . $filename);
    }

    if(!
    file_exists($filename))
    {
    print(
    "Template->make_filename(): Error - file $filename does not exist");
    }
    }
    return
    $filename;
    }

    private function
    loadfile($handle)
    {
    if(isset(
    $this->uncompiled_code[$handle]) && !empty($this->uncompiled_code[$handle]))
    {
    return
    true;
    }

    if(!isset(
    $this->files[$handle]))
    {
    print(
    "Template->loadfile(): No file specified for handle $handle");
    }

    $filename = $this->files[$handle];

    $str = implode("", @file($filename));
    if(empty(
    $str))
    {
    print(
    "Template->loadfile(): File $filename for handle $handle is empty");
    }
    $this->uncompiled_code[$handle] = $str;
    return
    true;
    }

    public function
    compile($code, $do_not_echo = false, $retvar = '')
    {
    $code = str_replace('\\', '\\\\', $code);
    $code = str_replace('\'', '\\\'', $code);

    $varrefs = array();
    preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
    $varcount = sizeof($varrefs[1]);
    for (
    $i = 0; $i < $varcount; $i++)
    {
    $namespace = $varrefs[1][$i];
    $varname = $varrefs[3][$i];
    $new = $this->generate_block_varref($namespace, $varname);
    $code = str_replace($varrefs[0][$i], $new, $code);
    }
    $code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', '\' . ((isset($this->_tpldata[\'.\'][0][\'\1\'])) ? $this->_tpldata[\'.\'][0][\'\1\'] : \'\') . \'', $code);

    $code_lines = explode("\n", $code);

    $block_nesting_level = 0;
    $block_names = array();
    $block_names[0] = ".";

    $line_count = sizeof($code_lines);
    for (
    $i = 0; $i < $line_count; $i++)
    {
    $code_lines[$i] = chop($code_lines[$i]);
    if(
    preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m))
    {
    $n[0] = $m[0];
    $n[1] = $m[1];

    if(
    preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n))
    {
    $block_nesting_level++;
    $block_names[$block_nesting_level] = $m[1];
    if(
    $block_nesting_level < 2)
    {
    $code_lines[$i] = '$_' . $n[1] . '_count = (isset($this->_tpldata[\'' . $n[1] . '.\'])) ? sizeof($this->_tpldata[\'' . $n[1] . '.\']) : 0;';
    $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
    $code_lines[$i] .= "\n" . '{';
    }
    else
    {
    $namespace = implode('.', $block_names);

    $namespace = substr($namespace, 2);

    $varref = $this->generate_block_data_ref($namespace, false);

    $code_lines[$i] = '$_' . $n[1] . '_count = (isset(' . $varref . ')) ? sizeof(' . $varref . ') : 0;';
    $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
    $code_lines[$i] .= "\n" . '{';
    }

    unset(
    $block_names[$block_nesting_level]);
    $block_nesting_level--;
    $code_lines[$i] .= '} // END ' . $n[1];
    $m[0] = $n[0];
    $m[1] = $n[1];
    }
    else
    {
    $block_nesting_level++;
    $block_names[$block_nesting_level] = $m[1];
    if(
    $block_nesting_level < 2)
    {
    $code_lines[$i] = '$_' . $m[1] . '_count = (isset($this->_tpldata[\'' . $m[1] . '.\'])) ? sizeof($this->_tpldata[\'' . $m[1] . '.\']) : 0;';
    $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
    $code_lines[$i] .= "\n" . '{';
    }
    else
    {
    $namespace = implode('.', $block_names);
    $namespace = substr($namespace, 2);
    $varref = $this->generate_block_data_ref($namespace, false);
    $code_lines[$i] = '$_' . $m[1] . '_count = (isset(' . $varref . ')) ? sizeof(' . $varref . ') : 0;';
    $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
    $code_lines[$i] .= "\n" . '{';
    }
    }
    }
    else if(
    preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m))
    {
    unset(
    $block_names[$block_nesting_level]);
    $block_nesting_level--;
    $code_lines[$i] = '} // END ' . $m[1];
    }
    else
    {
    if(!
    $do_not_echo)
    {
    $code_lines[$i] = 'echo \'' . $code_lines[$i] . '\' . "\\n";';
    }
    else
    {
    $code_lines[$i] = '$' . $retvar . '.= \'' . $code_lines[$i] . '\' . "\\n";';
    }
    }
    }
    $code = implode("\n", $code_lines);
    return
    $code ;
    }

    private function
    generate_block_varref($namespace, $varname)
    {
    $namespace = substr($namespace, 0, strlen($namespace) - 1);

    $varref = $this->generate_block_data_ref($namespace, true);

    $varref .= '[\'' . $varname . '\']';

    $varref = '\' . ((isset(' . $varref . ')) ? ' . $varref . ' : \'\') . \'';

    return
    $varref;
    }

    private function
    generate_block_data_ref($blockname, $include_last_iterator)
    {
    $blocks = explode(".", $blockname);
    $blockcount = sizeof($blocks) - 1;
    $varref = '$this->_tpldata';

    for (
    $i = 0; $i < $blockcount; $i++)
    {
    $varref .= '[\'' . $blocks[$i] . '.\'][$_' . $blocks[$i] . '_i]';
    }

    $varref .= '[\'' . $blocks[$blockcount] . '.\']';

    if(
    $include_last_iterator)
    {
    $varref .= '[$_' . $blocks[$blockcount] . '_i]';
    }
    return
    $varref;
    }

    private function
    get_cached_code($handle , $do_not_echo = false, $ret_var = '')
    {
    $cache_file = $this->cache_directory . '/' . md5($this->files[$handle]);

    $create_new_cache = 1;
    if(
    $cache_present = file_exists($cache_file))
    {
    $cache_stat = stat($cache_file);
    $template_stat = stat($this->files[$handle]);
    $create_new_cache = ($cache_stat['mtime'] < $template_stat['mtime'])?1:0 ;
    }

    $code = '';
    if(
    $create_new_cache)
    {
    if(!
    $this->loadfile($handle))
    {
    print(
    "Template->pparse(): Couldn't load template file for handle $handle");
    }

    if(!isset(
    $this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
    {
    $code = $this->compile($this->uncompiled_code[$handle], $do_not_echo, $ret_var);
    $this->compiled_code[$handle] = $code;
    }
    $fh = fopen($cache_file, 'w');
    fwrite($fh, $code);
    fclose($fh);
    } else {
    $fh = fopen($cache_file, 'r');
    $code = fread($fh, filesize($cache_file));
    fclose($fh);
    }
    return
    $code;
    }
    }

  12. #12
    Guest

    Predefinito

    Citazione Originalmente inviato da biccheddu Visualizza messaggio
    Allora, ho rifatto un po il tutto, ora ho la root strutturata in questo modo:
    Codice:
    |-/inc/
      |-template.class.php
    |-/tpl/
      |-/cache/
      |-index.tpl
    |-index.php
    In index.php ho:
    Codice PHP:
    <?php
    include('./inc/template.class.php' );

    $template = new Template();
    $template->set_rootdir = './tpl/';

    $template->set_filenames(array('body' => 'index.tpl'));

    $template->make_filename('body');
    $template->compile('body');
    $template->loadfile('body');

    $template->assign_vars(array(
    'ERROR_MESSAGE' => 'Error Message',
    )
    );

    $template->pparse('body');
    ?>
    Mentre in /inc/template.class.php ho cambiato in questo modo le var:
    Codice PHP:
    private $_tpldata = array();
    public
    $files = array();
    public
    $root = './tpl/';
    private
    $compiled_code = array();
    private
    $uncompiled_code = array();
    private
    $use_cache = true;
    private
    $cache_directory = './tpl/cache/';
    Ho provato anche a lasciare vuote public $root e private $cache_directory ma nulla!

    Come devo fare per utilizzarlo? Non riesco a capire il problema
    Ma sbagli .. make_filename e loadfile sono funzioni private!!

    Io l'ho usata così
    Codice PHP:
    include('template.php');

    $template = new Template();

    $template->set_filenames(array('body' => 'index.tpl'));

    $template->compile('body');

    $template->assign_vars(array(
    'ERROR_MESSAGE' => 'Error Message',
    )
    );


    $template->pparse('body');
    ?>
    index.tpl (per provarlo).
    Codice:
    <body>
    
    <p>{ERROR_MESSAGE}</p>
    </body>

  13. #13
    Guest

    Predefinito

    Risolto il metodo per stampare a video. Era un problema della funzione, che prendeva il file dalla root del sito, non dalla cartella /tpl/.

    Ho definito la cartella in public $root e ora funziona.

    Ora ho un problema con la cache invece.

    Mi vengono generati dei file senza estensione con i seguenti nomi file:
    Codice:
    53b863d5ef8623e4b0f4248ad67c8377
    Come posso sistemare, in modo da chiamare il file (in questo caso): tpl_index.html

    Vorrei salvare la cache in html, oppure in PHP, in modo da poterla svuotare e nel caso modificare senza problemi!

    Grazie in anticipo
    Ultima modifica di biccheddu : 16-05-2009 alle ore 21.34.09

  14. #14
    Guest

    Predefinito

    modifica questa parte
    Codice PHP:
    private function get_cached_code( $handle , $do_not_echo = false, $ret_var = '' )
    {
    $cache_file = $this->cache_directory . '/' . md5( $this->files[$handle] );
    //altro codice
    }
    la riga è la prima, quella che determina il nome del file salvato nella cache.

  15. #15
    Guest

    Predefinito

    Grazie stoner, nel frattempo ci ero arrivato, ma se modifico quel file, poi mi si incasina tutto il codice, ho aggiunto .html alla stringa e mi genera un file html, non so se alla fine funzioni o meno questa cosa della cache, ma va bene così

  16. #16
    palla000 non è connesso Utente attivo
    Data registrazione
    12-07-2008
    Residenza
    trieste
    Messaggi
    278

    Predefinito

    scusate ma a me da questo errore nella classe
    Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /membri/palla000/sito/classi/templatephpbb2.class.php on line 4
    qualcuno sa aiutarmi??

  17. #17
    Guest

    Predefinito

    Devi usare php5, altrimenti usa il codice che ho linkato tra i primi post, che c'è la classe anche per il 4

  18. #18
    palla000 non è connesso Utente attivo
    Data registrazione
    12-07-2008
    Residenza
    trieste
    Messaggi
    278

    Predefinito

    ah ok grazie

  19. #19
    Guest

    Predefinito

    Ragazzi, ho visto una cosa, non funziona l'include tramite i .tpl.

    Ho guardato un po la classe e bisogna agire sulla funzione compile().

    Userò INC io per include, almeno è più corto.

    Allora, quella di phpbb3 è così:
    Codice PHP:
    <?php

    preg_match_all
    ('#<!-- INC ([a-zA-Z0-9\_\-\+\./]+) -->#', $code, $matches);
    $include_blocks = $matches[1];
    $code = preg_replace('#<!-- INC [a-zA-Z0-9\_\-\+\./]+ -->#', '<!-- INC -->', $code);

    switch (
    $block_val[1])
    {
    case
    'INC':
    $temp = array_shift($include_blocks);
    $compile_blocks[] = '<?php ' . $this->compile_tag_include($temp) . ' ?>';
    $this->template->_tpl_include($temp, false);
    break;

    default:
    $this->compile_var_tags($block_val[0]);
    $trim_check = trim($block_val[0]);
    $compile_blocks[] = (!$no_echo) ? ((!empty($trim_check)) ? $block_val[0] : '') : ((!empty($trim_check)) ? $block_val[0] : '');
    break;
    }
    }

    function
    compile_tag_include($tag_args)
    {
    return
    "\$this->_tpl_include('$tag_args');";
    }
    ?>
    Come potrei integrarlo con la classe che ho ora??

    grazie in anticpo

Regole di scrittura

  • Non puoi creare nuove discussioni
  • Non puoi rispondere ai messaggi
  • Non puoi inserire allegati.
  • Non puoi modificare i tuoi messaggi
  •