[PHP] (Mail-)Template Klasse

08/28/2014 09:51 IchVerabschiedeMich#1
Hey Leute,

ich hab aus Spaß eine Klasse geschrieben mit der es möglich ist eine Text-Datei auszulesen und in dieser Variablen zu ersetzen oder andere Dateien zu inkludieren.

Ich nutze diese um Mail-Templates auszulesen damit diese nicht komplett hardcoded sind.

PHP Code:
<?php

/**
 * Lädt ein Template und ersetzt die Variablen darin.
 */

class Template
{
    
/**
     * Content des Templates
     *
     * @var string
     */
    
protected $content;

    
/**
     * Linker Delmeter für Template-Eigenen Code (Includes && Variablen)
     *
     * @var string
     */
    
protected $left_delimiter '{';

    
/**
     * Rechter Delimeter für Template-Eigenen Code (Includes && Variablen)
     *
     * @var string
     */
    
protected $right_delimiter '}';

    
/**
     * Zeichen um Variablen festzustellen
     *
     * @var string
     */
    
protected $variable_ident '$';

    
/**
     * Pfad zu E-Mail Templates
     *
     * @var string
     */
    
protected $template_path '';

    
/**
     * Gebundene Variablen werden hier gespeichert.
     *
     * @var array
     */
    
protected $variables = array();

    
/**
     * @return string
     */
    
public function getContent()
    {
        return 
$this->content;
    }

    
/**
     * @param $content
     * @return $this
     */
    
public function setContent($content)
    {
        
$this->content $content;
        return 
$this;
    }

    
/**
     * @param $delimiter
     * @return $this
     */
    
public function setLeftDelimiter($delimiter)
    {
        
$this->left_delimiter $delimiter;
        return 
$this;
    }

    
/**
     * @return string
     */
    
public function getLeftDelimiter()
    {
        return 
$this->left_delimiter;
    }

    
/**
     * @param $delimiter
     * @return $this
     */
    
public function setRightDelimiter($delimiter)
    {
        
$this->right_delimiter $delimiter;
        return 
$this;
    }

    
/**
     * @return string
     */
    
public function getRightDelimiter()
    {
        return 
$this->right_delimiter;
    }

    
/**
     * @param $ident
     */
    
public function setVariableIdentificator($ident)
    {
        
$this->variable_ident $ident;
    }

    
/**
     * @return string
     */
    
public function getVariableIdentificator()
    {
        return 
$this->variable_ident;
    }

    
/**
     * @param $path
     * @return $this
     */
    
public function setTemplatePath($path)
    {
        
$this->template_path $path;
        return 
$this;
    }

    
/**
     * @return string
     */
    
public function getTemplatePath()
    {
        return 
$this->template_path;
    }

    
/**
     * Prüft ob Datei vorhanden ist, ansonten wird $content als Content angesehen.
     *
     * @param string $content Pfad zum Template ansonsten direkt Content der Datei
     * @return bool
     */
    
public function Load($content '')
    {
        
// ### Wenn Leer einfach nichts machen.
        
if (empty($content)) {
            return 
true;
        }

        
// ### Prüfe ob Variable gesetzt worden ist
        
if (!$this->template_path) {

            
// ### Wenn nicht einfach leer machen.
            
$this->template_path '';

        }

        
// ### Prüfe ob Datei existiert
        
if (file_exists($this->template_path $content)) {

            
// ### Lade Content aus der Datei und setze diesen in eine Variable
            
$templateContent file_get_contents($this->template_path $content);
            
$this->setContent($templateContent);

            
// ### Verarbeite Content (Ersetze sachen wie Include etc)
            
$this->processContent();

            return 
true;

        }

        
// ### Lagere Content aus Datei oder String in eigene Variable
        
$this->setContent($content);

        
// ### Verarbeite Content (Ersetze sachen wie Include etc)
        
$this->processContent();

        return 
true;
    }

    
/**
     * Binde eine einzelne Variable im Template
     *
     * @param $variable Name der Variable
     * @param $value    Wert der Variable
     */
    
public function bind($variable$value)
    {
        return 
$this->bindMultiple(array(
            
$variable => $value,
        ));
    }

    
/**
     * Binde mehrere Variablen
     *
     * @param array $variables Array mit Variablen ($variable => $wert)
     */
    
public function bindMultiple(array $variables)
    {
        
// ### Setze vor jede Variable die festgelegten Trennzeichen
        
$temp $this->processVariables($variables);

        
// ### Ersetze Varaiblen mit dem zugehörigen Wert im Content
        
$temp str_replace(array_keys($temp), array_values($temp), $this->getContent());

        
// ### Setze content wieder in Variable
        
$this->setContent($temp);
    }

    
/**
     * Erweitertes ersetzen im Content des Templates durch funktionen wie "include"
     *
     * @return bool
     * @throws \Exception
     */
    
private function processContent()
    {
        
// ### Prüfe ob Funktion innerhalb des Templates vorhanden ist
        
if (!preg_match_all('/{include file=\"(.*)\"}/'$this->getContent(), $results)) {
            return 
true;
        }

        
// ### Lade Template in tempräre Variable
        
$tempContent $this->getContent();

        
// ### Iteriere durch alle ergebnisse
        
foreach ($results[0] as $key => $value) {

            
// ### Verinefache Dateinamen durch neue Variable
            
$file $results[1][$key];

            
// ### Prüfe ob zu includierende Datei existiert.
            
if (!file_exists($this->template_path $file)) {
                throw new \
Exception('file ' $this->template_path $file ' could not be found.');
            }

            
// ### Lade Content der zu includierenden Datei
            
$fileContent file_get_contents($this->template_path $file);

            
// ### Ersetze im Template mit dem content der Includierenden Datei
            
$tempContent str_replace($value$fileContent$tempContent);

        }

        
// ### Setze content wieder zurück
        
$this->setContent($tempContent);
    }

    
/**
     * Bringe Variablen in das richtige Format
     *
     * @param array $variables
     * @return array
     */
    
private function processVariables(array $variables)
    {
        
// ### Erstelle leeren Array
        
$temp = array();

        
// ### Iteriere durch Array
        
foreach ($variables as $key => $value) {

            
// ### Setze links und rechts die vom Benutzer festgelegten Trennzeichen
            
$key $this->left_delimiter $this->variable_ident $key $this->right_delimiter;

            
// ### Setze das ganze in einen neuen Array
            
$temp[$key] = $value;
        }

        return 
$temp;
    }

}
Aufruf:
PHP Code:
// Instanziere klasse
$tpl = new Template();

// Setze Pfad zu Templates
$tpl->setTemplatePath('pfad/zu/templates/');

// Lade Template
$tpl->Load('template.txt');

// Ersetze variablen
$tpl->bindMultiple(array(
    
'variable' => 'wert',
));

// Gebe verarbeitetes Template aus.
echo $tpl->getContent(); 
Ein Template kann dabei wie gefolgt aussehen:
Quote:
Sehr geehrter Herr {$name},

Ihr neues Passwort lautet: {$password}.

{include file="signature.txt"}
Gruß,
Padrio
08/28/2014 11:18 .Marcel'#2
Nett, kann man sicher gebrauchen. ;)