phptwigslim-4

How to access slim request interface inside controller


How to access Slim ServerRequestInterface in Controller.

Below is my working code

HomeController

<?php
namespace App\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\Twig;


class HomeController extends Controller
{

    public function index(Request $request, Response $response, $args)
    {

        return $this->view($request, 'home', ['name' => 'text']);  // My goal is to remove the $request passed
    }
}

Controller

<?php
namespace App\Controllers;

use Slim\Psr7\Factory\ServerRequestFactory;
use Slim\Views\Twig;
use Psr\Http\Message\ServerRequestInterface as Request;

class Controller
{

    public function view(Request $request, $tpl, $data)
    {

        $response = new \Slim\Psr7\Response();  // I can access response here. So passing response is not required

        $view = Twig::fromRequest($request); // I cannot access request here. So I need to pass it

        return $view->render($response, $tpl.'.html', $data);
    }
}

I tried suggestions from internet and got the error message below

Uncaught Error: Cannot instantiate interface Psr\Http\Message\ServerRequestInterface

or

Fatal error: Uncaught TypeError: Slim\Views\Twig::fromRequest(): Argument #1 ($request) must be of type Psr\Http\Message\ServerRequestInterface, string given

Note: this is a working code. All I need is to remove dependency of first argument $request

I tried to load twig separately as shown in doc. But slim needs the getBody()->write to be string.

I tried

$twig->fetch($tpl,$data)

but I got an error saying fetch is unknown.


Solution

  • I solved it with below code.

    I need to install twig

    composer require "twig/twig:^3.0"

    the load twig into my view

    public function view($tpl, $data)
        {
    
            $response = new \Slim\Psr7\Response();
    
            $loader = new \Twig\Loader\FilesystemLoader(ABSPATH . '/views');
    
            $twig   = new \Twig\Environment($loader, [
                'cache' => false, // ABSPATH.'/cached',
            ]);
    
            $html = $twig->render($tpl . '.html', $data);
    
            $response->getBody()->write($html);
    
            return $response;
        }
    

    Cons:

    The slim functions are not working.

    {{url_for('home')}}
    

    did not work