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
{
    // ...
}

#6

@PHLAK thanks for the information. Do I need to run composer update after this update to my composer.json?


#7

@AhmadKarim Yes, you have to run composer update after you’ve updated your composer.json file. However, after that you should be able to add any number of new classes in the namespace you used without re-running composer update.