How to load custom classes in slim 3


#1

I installed slim by composer my project directory structure is below,

projectrootdir/
projectrootdir/vendor

projectrootdir/src/routes/

projectrootdir/src/app

i want to load my custom classes in src/app directory all class are having namespace app so that i can use them in routes how to do so please somebody help,


#2

Get them autoloaded using composer:

"autoload": {
    "psr-4": {
        "App\\Controller\\": "app/controllers",
        "App\\Middleware\\": "app/middleware",
        "App\\Model\\": "app/models"	 
    }
},

You probally need to run composer dump-autoload after adding your classes.


#3

thank you very much @svl will definitely try this.


#4

It works like a charm… thanks


#5

@SVL’s answer will work but limits you to only the namespaces/paths defined. You could simplify this a bit and automatically load everything in the app folder under the App namespace like so:

"autoload": {
    "psr-4": {
        "App\\": "app/" 
    }
}

This would allow you to have any combination of folders under app/ as long as you give your classes the proper namespace. For example:

app/Controllers/SomeController.php

<?php

namespace App\Controller;

class SomeController
{
    // ...
}

app/Middleware/SomeMiddleware.php

<?php

namespace App\Middleware;

class SomeMiddleware
{
    // ...
}

app/Foo/Bar/Baz.php

<?php

namespace App\Foo\Bar;

class Baz
{
    // ...
}