I'm new to slim framework, and can't figure out how to use the autoloader to autoload my classes.
I created a app/models/myclass.php
but of course when I try to use it I get a class not found. I'm not sure which is the right way to autoload classes, or the naming convensions I should use. Should I do it via the composer.json somehow? I'm searching the net for several hours without any solid answer on that.
UPDATE:
Managed to do it like that:
namespace App\Model;
in Client.php$container['App\Model\Client'] = function ($c) {
return new App\Model\Client();
};
and routes.php:
$app->get('/client/ping/{id}', function ($request, $response, $args) {
$container = $this->getContainer();
$client=$container['App\Model\Client']; //instantiates a new Client
...
...
}
For autoloading of own classes you should use Composer
by adding some options to your composer.json
:
{
"require": {
"slim/slim": "^3.9"
},
"autoload": {
"psr-4": {
"My\\Namespace\\": "src/"
}
}
}
// index.php
require 'vendor/autoload.php';
$app = new \Slim\App();
$myClass = new \My\Namespace\MyClass();
After running composer update
composer will register your own namespaces and will autoload them for you.