Framework/src/Mvc/View.php

37 lines
925 B
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Phred\Mvc;
use Phred\Template\Contracts\RendererInterface;
abstract class View implements ViewWithDefaultTemplate
{
protected string $template = '';
public function __construct(protected RendererInterface $renderer) {}
/**
* Prepare data for the template. Subclasses may override to massage input.
*/
protected function transformData(array $data): array
{
return $data;
}
/**
* Render using transformed data and either the provided template override or the default template.
*/
public function render(array $data = [], ?string $template = null): string
{
$prepared = $this->transformData($data);
$tpl = $template ?? $this->defaultTemplate();
return $this->renderer->render($tpl, $prepared);
}
public function defaultTemplate(): string
{
return $this->template;
}
}