就像标题中所述,我希望使用Slim 4框架在控制器中渲染树枝模板。
我在Internet上进行了搜索,但没有找到适合我的且有充分解释的解决方案。
如果有人可以向我解释,我该如何使其工作。
这里是我的文件的代码:
index.php
<?php
use App\Controllers\HomeController;
use DI\Container;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
### Container ###
$container = new Container();
### Slim ###
AppFactory::setContainer($container);
$app = AppFactory::create();
### Twig ###
$container = $app->getContainer();
$container['view'] = function ($c) {
return $c;
};
$container['HomeController'] = function ($c) {
return new HomeController($c['view']);
};
### Routes ###
$app->get('/',HomeController::class . ":home");
$app->get('/home', HomeController::class . ":home");
### Run ###
$app->run();
HomeController.php
<?php
namespace App\Controllers;
use Psr\Container\ContainerInterface;
use Slim\Psr7\Request;
use Slim\Psr7\Response;
class HomeController
{
private $app;
public function __construct(ContainerInterface $app)
{
$this->app = $app;
}
public function home(Request $request, Response $response)
{
$this->app->get('view')->render($response, 'home.twig');
}
}
composer.json
{
"require": {
"slim/slim": "4.*",
"slim/psr7": "^1.0",
"slim/twig-view": "^3.0",
"php-di/php-di": "^6.0"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
项目结构
并且当我启动服务器时,控制台会给我:
PHP 7.3.11-0ubuntu0.19.10.2 Development Server started at Tue Feb 18 16:33:41 2020
Listening on http://localhost:8080
Document root is /home/thomas/Code/2020/S4/prog_web/homelogin/public
Press Ctrl-C to quit.
[Tue Feb 18 16:33:44 2020] PHP Fatal error: Uncaught Error: Cannot use object of type DI\Container as array in /home/thomas/Code/2020/S4/prog_web/homelogin/public/index.php:17
Stack trace:
#0 {main}
thrown in /home/thomas/Code/2020/S4/prog_web/homelogin/public/index.php on line 17
提前感谢。
set()
方法向容器添加服务。替换这些行:
set()
带有这些:
$container['view'] = function ($c) {
return $c;
};
$container['HomeController'] = function ($c) {
return new HomeController($c['view']);
};
然后您应该在
HomeController类的方法中返回响应(ResponseInterface):home()
$container->set('view', function () {
return \Slim\Views\Twig::create('../resources/views', ['cache' => false]);
});
$container->set('HomeController', function () use ($container) {
return new HomeController($container);
});
请注意,您的public function home(Request $request, Response $response)
{
return $this->app->get('view')->render($response, 'templates/home.twig');
}
文件位于templates目录中。
阅读Slim中有关home.twig
和Dependency Container的更多信息。>>