S
S
semki0962019-03-14 13:28:23
Slim Framework
semki096, 2019-03-14 13:28:23

How does passing container to controller (Slim php framework) work?

I created 2 containers

$container['view'] = new \Slim\Views\PhpRenderer('../app/templates/');

$container['HomeController'] = function($container){
    $HomeController = new \App\Controllers\Homecontroller($container['view']);
    return $HomeController;
};

Next, I created a router
//так работает
$app->get('/home', 'HomeController:home');

When we navigate to the /home link, we refer to the home method of the HomeController class.
Question. Whether correctly I understand that the appeal goes through the container? If I write as below and refer directly to the function, then this will not work, apparently the view object is not passed
//так не работает, видимо не передается объект view
$app->get('/home', '\App\Controllers\Homecontroller:home');

I would be grateful if you explain how it works, how the transfer of the container to the controller works step by step. Here is my controller
namespace App\Controllers;

use \Slim\Views\PhpRenderer;

class HomeController
{
    public $view;

    public function __construct(PhpRenderer $view) {
        
        $this->view = $view;
    }
    
    public function home($request, $response) {
        
        return $this->view->render($response, 'index.phtml');
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2019-03-14
@semki096

When passing a string, the router will first look to see if the container has such an object, and if so, return it. If not, it will try to interpret the string as the name of the action controller and create a new instance.
In the second case, the container itself will be passed to the controller constructor, from which you can access the View.
In turn, if you create an object in a container like this
then this entry should work
In theory, controllers can not be included in the container at all, and access to dependencies can be obtained through the passed container

public function __construct($c) {
  $this->container = $c;
  
  $this->container->get('view');
}

But this is a moot point.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question