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
...
...
}
Composer is PHP's dependency manager tool. Composer allows you to specify libraries that are need for a project, and will automatically include those libraries along with their dependencies. Composer also allows you to create your own packages and share them via the Packagist website.
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require __DIR__ . '/../
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.
Add this in composer.json file Where app1 is the name of the folder you want to Autoload.
"autoload": {
"psr-4":{
"app1\\": "anything"
}
}
After doing this run this in cmd (via composer)
composer dump-autoload -o
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With