I’m using Slim to create a simple API. I would like to use a controller class called from the router.
This is the relevant part of my router.php
$app->group('/api/course/v1', function () use ($app) {
$app->post('', '\Course:handlePost');
});
This is the relevant part of my dependencies.php:
// autoload class and make sure logger is available
$container['\Course'] = function($c) {
// >> include_once __DIR__ . '/controllers/courseController.php';
return new App\Controller\Course($c);
};
namespace App\Controller;
class Course {
private $app;
private $logger;
public function __construct($app) {
$this->app = $app;
$this->logger = $app->logger;
}
/**
* Handle the Course POST request
*/
public function handlePost() {
$this->logger->info("Coursecontroller::handlePost route called");
echo "Hello";
}
}
This works if i use the include in dependencies.php, however i want the controller (and all classes in that namespace) to autoload instead of having to include them. I understand that I can do this by using autoload in composer.json (as shown above) but I still get class not found errors instead Type: Error Message: Class ‘App\Controller\Course’ not found File: /{path to slim root}/src/dependencies.php
I tried using composer dump-autoload but to no avail.
Thanks for your help guys! But I didn’t want to use the spl_autoload functions, because the Slim framework uses the composer/autoload functions and I’d rather not use two methods in the same project. But I couldn’t get them to work. Now I know why: It’s all about naming conventions.
My class filename is CourseController.php but the class in there is named Course. Therefore the autoload can’t find the class. I changed the classname to CourseController and now everything works, without spl_autoload but using the composer autoload: