Description
Thank you for this magnificent framework, which has helped me a lot in learning how PHP works internally.
I recently discovered Symfony, and in the future I intend to enroll my applications in that framework. While I prepare my infrastructure for that migration, I'm using your framework, with which I'm quickly migrating a website that runs on WordPress to pure PHP code.
Forgive this long introduction...
I have a question regarding templates management. On the one hand, I see two classes called MVCTemplateViewer
and PHPTemplateViewer
. In some methods of those classes, I see code that appears to include or format content based on Twig templates, but Twig doesn't appear anywhere in the project files.
What is the point of these two classes and why is there nothing about Twig in the project?
Incorporating Twig
Since I'm using Twig in my code, I created this class:
<?php
declare(strict_types=1);
namespace Core;
class TwigTemplateViewer implements TemplateViewerInterface
{
public function render(string $template, array $args = []): string
{
static $twig = null;
if ($twig === null) {
$loader = new \Twig\Loader\FilesystemLoader(dirname(__DIR__) . '/App/Views');
$options =[
'cache' => 'compilation_cache',
'debug' => $_ENV["ENVIRONMENT"]=='dev'
];
$twig = new \Twig\Environment($loader,$options);
if($_ENV["ENVIRONMENT"]=='dev')
{
$twig->addExtension(new \Twig\Extension\DebugExtension());
}
return $twig->render($template, $args);
}
}
}
Then, I created files with the Twig templates, and it works perfectly in the controllers:
class Products extends Controller
{
public function __construct(private Product $model)
{
}
public function index(): Response
{
$products = $this->model->findAll();
//Note the use of index.html.twig instead of .php index.mvc.php
return $this->view("Products/index.html.twig", [
"products" => $products,
"total" => $this->model->getTotal()
]);
}
// ...
}
How to use Twig in error messages?
Basically, my question is: how can I also integrate Twig to display error messages? Is this a good practice or is it better to display 500 error messages in a .php
page, independent of the theme (Twig).
I see that they are displayed from the class ErrorHandler
, but how can I incorporate Twig to also display error messages within the application theme, and not in a separate .php
file?