Slim3 不会将您绑定到特定的文件夹结构,但它确实(而是)假设您使用 composer 并使用 PSR 文件夹结构之一。
就个人而言,这就是我使用的(嗯,一个简化版本):
在我的索引文件 /www/index.php 中:
include_once '../vendor/autoload.php';
$app = new \My\Slim\Application(include '../DI/services.php', '../config/slim-routes.php');
$app->run();
在 /src/My/Slim/Application.php 中:
class Application extends \Slim\App
{
function __construct($container, $routePath)
{
parent::__construct($container);
include $routePath;
$this->add(new ExampleMiddleWareToBeUsedGlobally());
}
}
我在 DI/services.php 中定义了所有依赖注入,在 config/slim-routes.php 中定义了所有路由定义。请注意,由于我在 Application 构造函数中包含路由,因此它们将 $this 引用包含文件中的应用程序。
然后在 DI/services.php 你可以有类似的东西
$container = new \Slim\Container();
$container['HomeController'] = function ($container) {
return new \My\Slim\Controller\HomeController();
};
return $container;
在 config/slim-routes.php 类似
$this->get('/', 'HomeController:showHome'); //note the use of $this here, it refers to the Application class as stated above
最后是你的控制器 /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');
}
}
此外,返回 json 的最佳方式是使用return $response->withJson($toReturn)