Rozbudowa TemplateEngine do naszego projektu MVC – dodajemy kolejną dyrektywę. Do dzieła!

Nasz sth3.php ma wyglądać tak:

<h1>{{ $site_name }}</h1>
@if(isset($name))
<p> Hello [b]{{ $name }}[/b]</p>
@else
<p>Hello guest</p>
@endif

@isset($name2)
<p> Hello [b]{{ $name2 }}[/b]</p>
@empty
<p>Hello guest2</p>
@endif

Wzory trzeba aktualizować:

protected static $patterns = [
    [
        "pattern" => '/\{\{\s*(\$.*?)\s*\}\}/',
        "replace" => "<?php echo $1; ?>" 
    ],
    [
        "pattern" => '/\[b\](.*?)\[\/b\]/s',
        "replace" => "<b>$1</b>" 
    ],
    [
        "pattern" => '/@if\((.*)\)/',
        "replace" => "<?php if ($1) : ?>" 
    ],
    [
        "pattern" => '/@else/',
        "replace" => "<?php else : ?>" 
    ],
    [
        "pattern" => '/@endif/s',
        "replace" => "<?php endif; ?>" 
    ],
    [
        "pattern" => '/@isset\((.*)\)/',
        "replace" => "<?php if(isset($1)) : ?>" 
    ],
    [
        "pattern" => '/@empty/',
        "replace" => "<?php else : ?>" 
    ],
];

Teraz sprawdzamy:

<?php 

class TemplateEngine
{
  private array $globalTemplateData = [];

  protected static $patterns = [
    //(...)
];

  //(...)
}

$template = new TemplateEngine(__DIR__);
$template->addGlobal('site_name', 'MyApp');
echo $template->renderTemplate('sth3.php', ['name' => 'John']);

Ok, sprawdzamy dalej:

<?php 

class TemplateEngine
{
  private array $globalTemplateData = [];

  protected static $patterns = [
    //(...)
];

  //(...)
}

$template = new TemplateEngine(__DIR__);
$template->addGlobal('site_name', 'MyApp');
echo $template->renderTemplate('sth3.php', ['name2' => 'John']);

Wszystko działa jak należy.