Shahzaib Idrees Baluch Shahzaib Idrees Baluch - 1 month ago 10
PHP Question

phpSlim twg-view not working

i am getting error in my slim framework application. i don't know why twig-view is not working. twig-view is downloaded in vendor directory.
this is my index file

<?php
require __DIR__ . '/vendor/autoload.php';
// Settings
$config = [
'settings' => [
'displayErrorDetails' => true,
'addContentLengthHeader' => false,
],
];

$app = new \Slim\App($config);

// Get container
$container = $app->getContainer();

// Register component on container
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig( __DIR__ . '/resources/views', [
'cache' => false
]);

// Instantiate and add Slim specific extension

$view->addExtension(new Slim\Views\TwigExtension(
$container['router'],
$container['request']->getUri()

));

return $view;
};

// Home
$app->get('/home','index');



function index($request, $response, $args)
{
return $this->view->render($response, 'home.twig'); // here is the error
}

$app->run();


i am getting error om $this keyword
error details

Details

Type: Error
Message: Using $this when not in object context
File: C:\xampp\htdocs\slim\api\index.php
Line: 42

Answer

You are declaring route incorectly, try

// This callback will process GET request to /index URL    
$app->get('/index', function($request, $response, $args) {
    return $this->view->render($response, 'home.twig');
});

Instead of declaring a function, you should call $app method to register a route.

EDIT

It is also possible to "separate" route declaration from the callback. You can create separate classes (a-la controllers in MVC pattern), like this:

// Declaring a controller class with __invoke method, so it acts as a function
class MyController
{

    public function __invoke($request, $resposne)
    {
        // process a request, return response
    }

}

// And here's how you add it to the route
$app->get('/index', 'MyController');

I suggest you read the appropriate section of the documentation. It's dead simple.

Comments