B
B
Banny_Boom2015-05-29 09:38:19
PHP
Banny_Boom, 2015-05-29 09:38:19

How to use Twig in MVC, in a model?

How to properly use template engine in mvc?
Twig->render etc, should this be in the model?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Komarov, 2015-05-29
@Banny_Boom

Model, in simple terms, is a class that describes the structure of a particular table + getters and setters. Your controller will give the page. I do this in my project:
The class responsible for the work of the twig:

<?php
namespace View;

use Controller\Error;
use Twig_Environment;
use Twig_Loader_Filesystem;

class TwigView implements IView
{
    /**
     * @var Twig_Environment
     */
    private $twig;
    /**
     * @var Twig_Loader_Filesystem
     */
    private $loader;
    /**
     * @var string
     */
    private $template;
    /**
     * @var array
     */
    private $params;

    /**
     * @param string $template Имя шаблона
     * @param array $params Передаваемые параметры
     */
    public function __construct($template, $params)
    {
        $this->loader = new Twig_Loader_Filesystem(TEMPLATE_DIR);
        $this->twig = new Twig_Environment($this->loader);
        $this->template = $template;
        $this->params = $params;
    }

    /**
     * @return string
     */
    public function render()
    {
        try {
            return $this->twig->render($this->template, $this->params);
        } catch (\Twig_Error_Loader $e) {
            $error = new Error();
            $error->index404();
        }
    }
}

In the controller (output method of all users of the system):
public function index()
    {
        $this->isAuthorized('users');
        try {
            $twig = new TwigView('Users/ShowAllUsers.twig',
                [
                    'session' => $_SESSION,
                    'user' => $this->em->getRepository('Model\User')->getAll()
                ]
            );
            print $twig->render();
        } catch (DatabaseException $e) {
            $error = new Error();
            $error->index1010($e->getMessage());
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question