PHP Slim 3 Framework - 我可以把我的控制器文件放在哪里?

PHP Slim 3 Framework - where can I put my controller file?

我在容器中注册了一个控制器,但它似乎无法正常工作,因为它与正确的位置不匹配。

\slim\src\routes.php

<?php
// Routes
$app->get('/dd', 'App\controllers\HomeController:home');

\slim\App\controllers\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 应用程序错误:

Type: RuntimeException Message: Callable App\controllers\HomeController does not exist File: D:\htdocs\slim\vendor\slim\slim\Slim\CallableResolver.php Line: 90

最后,我也参考了这些文章: https://www.slimframework.com/docs/objects/router.html#container-resolution

PHP Slim Framework 创建控制器 PHP Slim Framework Create Controller

如何在 Slim Framework 3 上创建中间件?

将 psr-4 添加到您的 composer 文件中,以便您能够调用您的命名空间。

{
    "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
    }

希望这对您有所帮助...:)