Answer the question
In order to leave comments, you need to log in
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;
};
//так работает
$app->get('/home', 'HomeController:home');
//так не работает, видимо не передается объект view
$app->get('/home', '\App\Controllers\Homecontroller:home');
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
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');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question