Request $request, Response $Response in an abstract controller class SLIM FRAMEWORK PHP

Asked

Viewed 89 times

0

Good afternoon to you all. I’m studying Slim Framework 3.12 for PHP, and I’m building my controllers to be called on the routes. I have a class abstract called Controller.php that I use to initialize my objects from the drivers that extend it (using extends).

Thus:

**<?php**


namespace App\Controllers;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;


abstract class Controller {

    public $request;
    public $response;

    function __construct(Request $request, Response $response) {

        $this->request  = $request;
        $this->response = $response;

    }


}
**?>**

But I can’t get $request and $Answer, within this class they’re not getting Resquest and Response. But if I do it in my concrete classes, I can get access:

**<?php**

namespace App\Controllers;
use App\Controllers\Controller;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\Container;

class MyController extends Controller{


    public function index(Request $request, Response $response){
         $request->getMethod();
         $response->getStatusCode();
         echo ("Deu certo");
    }

}
**?>**

How do I get access in my Abstract class? Because every controller needs this Request and Response... .

Grateful for the attention.

1 answer

0

Good afternoon, you guys, I was able to solve by doing the following, instead of putting as parameter in the constructor method of the abstract class Controller.php os: Request $request and Response $Response, subsitituí by Container $c , thus:

<?php

namespace App Controllers; use Psr Http Message Serverrequestinterface as Request; use Psr Http Message Responseinterface as Response;

Abstract class Controller {

public $request;
public $response;

function __construct(\Slim\Container $c) {

    $this->request  = $c->request;
    $this->response = $c->response;

}

} ?>

I found this solution on another web page(https://github.com/slimphp/Slim/issues/1750#issuecomment-179232639) , but wanted to understand why, why Slim stores it inside this Class Container, wanted to know how this Container Class works, to better understand why it worked(I already know what Dependency Injection is).

Someone to enlighten me ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.