-2

I read the documentation here about creating middleware. But which folder or file i must be create it? Documentation is not contain this information.

Under the src folder i have middleware.php.

For example i want to get post information like this:

$app->post('/search/{keywords}', function ($request, $response, $args) {
    $data = $request->getParsedBody();
    //Here is some codes connecting db etc...
    return json_encode($query_response);
});

i made this under the routes.php but i want to create class or middleware for this. How can i do? Which folder or file i must be use.

devugur
  • 1,339
  • 1
  • 19
  • 25
  • How would that be middleware? Are you looking to make controllers maybe? https://www.slimframework.com/docs/objects/router.html#registering-a-controller-with-the-container. As for the question you can make whatever middleware folder you want and the files that make sense. – nerdlyist Feb 01 '17 at 13:35
  • ok. i want to make class HomeController . Where i can create the HomeController.php? (Under the which folder, src?) – devugur Feb 01 '17 at 13:37
  • 1
    `src/Controller` should be good. – nerdlyist Feb 01 '17 at 14:21
  • You can put the file everywhere you want. – jmattheis Feb 01 '17 at 14:30

1 Answers1

1

Slim3 does not tie you to a particular folder structure, but it does (rather) assume you use composer and use one of the PSR folder structures.

Personally, that's what I use (well, a simplified version):

in my index file /www/index.php:

include_once '../vendor/autoload.php';

$app = new \My\Slim\Application(include '../DI/services.php', '../config/slim-routes.php');
$app->run();

In /src/My/Slim/Application.php:

class Application extends \Slim\App
{
    function __construct($container, $routePath)
    {
        parent::__construct($container);

        include $routePath;
        $this->add(new ExampleMiddleWareToBeUsedGlobally());

    }
}

I define all the dependency injections in DI/services.php and all the route definitions in config/slim-routes.php. Note that since I include the routes inside the Application constructor, they will have $this refer to the application inside the include file.

Then in DI/services.php you can have something like

$container = new \Slim\Container();
$container['HomeController'] = function ($container) {
    return new \My\Slim\Controller\HomeController();
};
return $container;

in config/slim-routes.php something like

$this->get('/', 'HomeController:showHome'); //note the use of $this here, it refers to the Application class as stated above

and finally your controller /src/My/Slim/Controller/HomeController.php

class HomeController extends \My\Slim\Controller\AbstractController
{
    function showHome(ServerRequestInterface $request, ResponseInterface $response)
    {
        return $response->getBody()->write('hello world');
    }
}

Also, the best way to return json is with return $response->withJson($toReturn)

malte
  • 1,439
  • 1
  • 11
  • 12