David Legatt David Legatt - 4 months ago 35
PHP Question

Silex and autloading controller classes

I am having problems getting class autoloading to work in the Silex skeleton I am putting together. I have this working in another project, but I can't figure out what I am doing wrong here.
My directory looks like this:

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


Here is my 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>');
}
}


and composer.json

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


Whenever I try to open index.php/hello/world in a browser, I get this error:

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

Answer

Your psr-4 is not working. Add a dot before '/src'

"App\\": "./src"

or move the slash to the end

"App\\": "src/"

or just remove the slash. The path must be relative.