0

I have 2 classes, first is controller and second one is the class that load Twig.
This is working fine, but i'm curious if i can do it like this: echo $twig->render('index.html');
Maybe different solution to load Twig in controller?

Twig class taken from: Include twig loader from external file

Home.php

<?php 
namespace Controllers;

use Helpers\Twig;

class Home {    
    public static function index()
    {
        echo Twig::$twig->render('index.html');
    }
}
?>

Twig.php

<?php 
namespace Helpers;

class Twig {
    public static $twig;

    public static function init() {
        $loader = new \Twig_Loader_Filesystem(__DIR__.'/../views');
        self::$twig = new \Twig_Environment($loader);
    }
}

Twig::init();
?>
exexe
  • 196
  • 1
  • 13

1 Answers1

2

Yeah, your are doing few things wrong there:

  • you really should not combine controller and view responsibilities without a good reason (the "why" part is a bit compicated, you can read about it here later)

  • you should stop abusing static keyword - those static classes are actually an old hack for "namespaced functions" from pre php5.3 age: it's not OOP, it's procedural code

  • stop using ?> at the end of class files: it is not necessary and it tends to cause "header already sent" errors

As for the main issue: you should not be accessing a global loader, but instead passing the templating engine (in this case: Twig_Environment) as a dependency. You can see a very simplified example in practice here.

If you will be using the Twig for templating, then there really isn't a more simplified way for initializing the whole thing (even if you are resorting to procedural code). And the whole "too many things are being loaded" is kinda bullshit, since in production environment majority of your code will end up in the OpCopde cache (you can google that) and since PHP 5.5 the simple class initialization is a very cheap process.

As for OOP in general: just go through the list of lectures listed here :P

... this ended up more like a long form comment

tereško
  • 58,060
  • 25
  • 98
  • 150