我在容器中注册了一个控制器,但似乎没有用,因为它与正确的位置不匹配。
\苗条\ SRC \ routes.php文件
<?php
// Routes
$app->get('/dd', 'App\controllers\HomeController:home');
\苗条\应用\控制器\ HomeController.php
<?php
class HomeController
{
protected $container;
// constructor receives container instance
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public function home($request, $response, $args) {
// your code
// to access items in the container... $this->container->get('');
return $response;
}
public function contact($request, $response, $args) {
// your code
// to access items in the container... $this->container->get('');
return $response;
}
}
我的项目文件夹结构:
\slim
\public
index.php
.htaccess
\App
\controllers
HomeController.php
\src
dependencies.php
middleware.php
routes.php
settings.php
\templates
index.phtml
\vendor
\slim
也许我应该设置 \ slim \ src \ settings.php ?
因为它显示了Slim Application Error:
类型:RuntimeException消息:可调用 App \ controllers \ HomeController不存在文件: D:\ htdocs \ slim \ vendor \ slim \ slim \ Slim \ CallableResolver.php行:90
最后,我也参考了这些文章: https://www.slimframework.com/docs/objects/router.html#container-resolution
PHP Slim Framework创建控制器 PHP Slim Framework Create Controller
如何在Slim Framework 3上创建中间件? How can i create middleware on Slim Framework 3?
答案 0 :(得分:0)
您忘记在HomeController
文件中定义命名空间,将此行添加到HomeController.php
的顶部:
namespace App\controllers\HomeController;
答案 1 :(得分:0)
将psr-4添加到您的作曲家文件中,以便您可以调用名称空间。
{
"require": {
"slim/slim": "^3.12
},
"autoload": {
"psr-4": {
"App\\": "app"
}
}
}
此PSR描述了从文件路径自动加载类的规范。然后在您的routes.php文件中,将其添加到顶部:
<?php
use app\controllers\HomeController;
// Routes
$app->get('/dd', 'App\controllers\HomeController:home');
最后在您的HomeController.php文件中添加:
<?php
namespace app\controllers;
class HomeController
{
//.. your code
}
希望这对您有帮助...:)