Help using slim/twig-view (subclasses)

Hi,

The docs show how to get slim/twig-view working, but does so in spaghetti style.

I’m trying to do it more tidily but am having trouble getting it working, I get an error

Message: Call to a member function render() on null

My index.php looks like this:

$container = $app->getContainer();
$view = new \CMS\View\Main($container);
$container['view'] = $view->getTwig();
$app->get('/go/{pageset}','\CMS\Controller\Unauth\Go:go')->setName('go');

\CMS\View\Main looks like this:

<?php
namespace CMS\View;
use \Slim\Views\Twig;
use \Slim\Views\TwigExtension;
use \CMS\Config\SlimConf;
class Main {
protected $ci;
private $view;
//Constructor
public function __construct(\Slim\Container $ci) {
    $this->ci = $ci;
}
public function getTwig() {
   $this->view = new Twig ( SlimConf::TWIG_TEMPLATE_DIR, [
        'cache' => SlimConf::TWIG_CACHE_DIR
    ]);
    $basePath = rtrim(str_ireplace('index.php', '', $this->ci['request']->getUri()->getBasePath()), '/');
    $this->view->addExtension(new TwigExtension($this->ci['router'], $basePath));
    return $this->view;
}
}
?> 

My Go.php glass looks like this:

namespace CMS\Controller\Unauth;
class Go {
protected $ci;
private $pageset;
//Constructor
public function __construct(\Slim\Container $ci) {
    $this->ci = $ci;
}
public function go($request, $response, $args) {
    $this->pageset=$args['pageset'];
    return $this->ci->view->render($response,'master.html');
}
}

If I replace the view return with something like this:

return $response->withStatus(403)
                    ->write("FOOBAR !");

It returns ok. So my Slim & class is setup generally ok, its just the Twig that’s broken !

I think you may need to rework your index.php a bit to something more like this:

$container = $app->getContainer();
$container['view'] = function () {
    $view = new \CMS\View\Main($container);
    $view->getTwig();
};
$app->get('/go/{pageset}','\CMS\Controller\Unauth\Go:go')->setName('go');

Slim uses Pimple on the back end for dependencies. When using Pimple, you have to define your dependencies as callbacks. The use of callbacks allows your code to only create service instances when the service is actually needed.