S
S
semki0962017-11-01 22:52:21
Slim Framework
semki096, 2017-11-01 22:52:21

How does this router magic work in Slim (for example)?

Here is the router

$app->get('/', 'App\Controllers\UserController:listUsers');

Here is the controller
class UserController {

  protected $container;   

  public function __construct($container) {
        $this->container = $container;
  }
    
    public function listUsers($request, $response){       
        return $this->container->view->render($response, 'home.twig');
    }
    
}

The question is - we don’t pass the container in the router, how then does this container get into the constructor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
@
@smple, 2017-11-03
@semki096

This is called di (dependency injection)
in $app->get the string 'App\Controllers\UserController:listUsers' is converted to App\Controllers\UserController and the listUsers method with explode(':', 'App\Controllers\UserController:listUsers' );
After that, using the dependency injection tool (in the case of slim, Pimple is used with its object loaders), an object is created and by default passes itself to the constructor (so you get container in the constructor which is essentially a pimple object that implements psr\container
Next is a call to object that was received in the last step of the selected method if it was specified with current.request and current.response arguments that are defined inside pimple
Well, here your code is already being executed, you ask pimple for the container that is responsible for the view, by default it is a Twig object like and it calls the render method in which you seem to have the arguments mixed up (at the beginning the template name, then the arguments for this template in the form of an array )
The template is rendered at the output, a string is obtained, this string is placed in the response inside the app after calling the method, if the result of the method is not response, and then this response is sent to the user
In general terms, something like this, with its own nuances, and slim also has several versions that differ significantly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question