Как создать контроллер в slim 4?

67
26 сентября 2021, 01:50

В официальной документации slim 4 написано

Container Resolution You are not limited to defining a function for your routes. In Slim there are a few different ways to define your route action functions.

In addition to a function, you may use:

container_key:method Class:method Class implementing __invoke() method container_key This functionality is enabled by Slim’s Callable Resolver Class. It translates a string entry into a function call. Example:

$app->get('/', '\HomeController:home');
Alternatively, you can take advantage of PHP’s ::class operator which works well with IDE lookup systems and produces the same result:
$app->get('/', \HomeController::class . ':home');
In this code above we are defining a / route and telling Slim to execute the home() method on the HomeController class.

Slim first looks for an entry of HomeController in the container, if it’s found it will use that instance otherwise it will call it’s constructor with the container as the first argument. Once an instance of the class is created it will then call the specified method using whatever Strategy you have defined.

Registering a controller with the container Create a controller with the home action method. The constructor should accept the dependencies that are required. For example:

<?php
class HomeController
{
    protected $view;
    public function __construct(\Slim\Views\Twig $view) {
        $this->view = $view;
    }
    public function home($request, $response, $args) {
      // your code here
      // use $this->view to render the HTML
      return $response;
    }
}

Create a factory in the container that instantiates the controller with the dependencies:

$container = $app->getContainer();
$container->set('HomeController', function (ContainerInterface $c) {
    $view = $c->get('view'); // retrieve the 'view' from the container
    return new HomeController($view);
});

This allows you to leverage the container for dependency injection and so you can inject specific dependencies into the controller.

Но к сожалению, повторив всё это, я получаю ошибку

"Callable \HomeController does not exist"

Answer 1

Ошибка возникает из-за того, что Ваш контроллер находится в контейнере под ключом HomeController, а приложение ищет обработчик по ключу \HomeController.

Попробуйте указать одинаковые значения в роутинге и инициализации контейнера.

$container->set(\HomeController::class, function (ContainerInterface $c) {
    $view = $c->get('view'); // retrieve the 'view' from the container
    return new HomeController($view);
});
// ...
$app->get('/', \HomeController::class . ':home');
READ ALSO
symfony, зачем аннотации

symfony, зачем аннотации

Всем привет, я примерно 6-7 работаю бэкенд разработчиком, всегда писал на чистом php, работаю только с какими-то библиотеками из packagistНачал изучать...

134
Реализация интерфейса php codeigniter interface

Реализация интерфейса php codeigniter interface

При создании интерфейса выходит вот такая ошибка

124
Почему не работает условие? php

Почему не работает условие? php

ну все равно выдаёт false! Как так получается?

106