Silex 和自动加载控制器 类

Silex and autloading controller classes

我在让 class 自动加载在我组装的 Silex 骨架中工作时遇到问题。我在另一个项目中工作,但我不知道我在这里做错了什么。 我的目录如下所示:

root
 -src
    -Controller
       -HelloController.php
    -app.php
 -vendor
 -web
   -index.php
 -composer.json

这是我的 index.php

<?php
$app = require __DIR__.'/../src/app.php';
$app->run();

app.php

<?php
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->get("/hello/{name}", 'App\Controller\HelloController::hello');
return $app;

HelloController.php

<?php

namespace App\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;

class HelloController
{
    public function hello($name)
    {
        return new Response('<html><head></head><body><h1>Hello, '.$name.'</h1></body></html>');
    }
}

和composer.json

{
    "require": {
        "silex/silex": "^1.3"
    },
    "autoload": {
      "psr-4": {
        "App\": "/src"
      }
    }
}

每当我尝试在浏览器中打开 index.php/hello/world 时,我都会收到此错误:

InvalidArgumentException in ControllerResolver.php line 153: 
Class "App\Controller\HelloController" does not exist

您的 psr-4 不工作。 '/src'

前加点
"App\": "./src"

或将斜杠移至末尾

"App\": "src/"

或者只删除斜杠。路径必须是相对的。

在composer.json中变化

"App\": "/src"

"App\": "src"

你可以找到 带有控制器的 SilexSkeleton php 类 GitHub 上的示例:https://github.com/jaresz/SilexSkeleton