Php 在Controller-Slim 4框架中渲染细枝模板
正如标题中所说,我希望使用Slim 4框架在controller中呈现细枝模板 我在互联网上搜索过,但没有找到一个适合我的解决方案,也没有得到很好的解释 如果有人能向我解释,我怎样才能让这一切顺利进行 下面是我的文件的代码: index.phpPhp 在Controller-Slim 4框架中渲染细枝模板,php,twig,slim,Php,Twig,Slim,正如标题中所说,我希望使用Slim 4框架在controller中呈现细枝模板 我在互联网上搜索过,但没有找到一个适合我的解决方案,也没有得到很好的解释 如果有人能向我解释,我怎样才能让这一切顺利进行 下面是我的文件的代码: index.php <?php use App\Controllers\HomeController; use DI\Container; use Slim\Factory\AppFactory; require __DIR__ . '/../vendor/auto
<?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();
项目结构
当我启动服务器时,控制台会给我:
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
提前感谢。您不能将DI\Container对象用作数组。您应该使用方法将服务添加到容器中 更换这些线路:
$container['view'] = function ($c) {
return $c;
};
$container['HomeController'] = function ($c) {
return new HomeController($c['view']);
};
有了这些:
$container->set('view', function () {
return \Slim\Views\Twig::create('../resources/views', ['cache' => false]);
});
$container->set('HomeController', function () use ($container) {
return new HomeController($container);
});
然后,您应该在HomeController类的home()方法中返回一个响应(ResponseInterface):
public function home(Request $request, Response $response)
{
return $this->app->get('view')->render($response, 'templates/home.twig');
}
请注意,您的home.twig
文件位于templates目录中
阅读有关和的更多信息。这是否回答了您的问题?到底是什么问题?我不认为给出的错误消息与TwigThank有任何联系,但现在php告诉我:`php致命错误:Class DI\Container包含3个抽象方法,因此必须声明为抽象或实现其余方法`。你知道为什么吗?你的项目结构和我的非常相似。这是一本书。希望这有帮助。
$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');
}