Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: load custom class from new custom directory

Tags:

laravel-4

I have currently added a new folder to my app directory for all my 'libraries'. I keep recieving an error that the class is not found, this is what I do:

I have added it to the composer.json file in the autoload value:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/services",
        "app/facades",
        "app/libraries" --> here
    ]
},

Added it to my global.php file in the classloader:

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/libraries', --> here

));

Created an alias for it in app.php:

'aliases' => array(

    'App'               => 'Illuminate\Support\Facades\App',
    'Session'           => 'Illuminate\Support\Facades\Session',
    ...
    'SimpleImage'       => 'App\Libraries\abeautifulsite\SimpleImage', --> here

),

And called the class in my controller:

$img = new SimpleImage($file);

The error I keep receiving is that the class is not found. What am I missing?

ErrorException (E_UNKNOWN) 
Class 'App\Libraries\abeautifulsite\SimpleImage' not found

(PS. I did composer dump-autoload in terminal)

like image 605
user2381011 Avatar asked Jan 10 '23 06:01

user2381011


1 Answers

The best way to add a custom folder in your Laravel project is using PSR-4.

First of all create your custom directory in /app, for example:

/app/YourName/libraries

now open composer.json and just after the autoload -> classmap add the psr-4 structure:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/services",
        "app/facades"
    ],
    "psr-4": {
        "YourName\\": "app/YourName"
    }
},

Note that I removed your /app/libraries row, then run:

composer dump-autoload

In this way all the folders you will add in YourName folder will be loaded.

For example:

app/ChristianGiupponi/libraries

and

"psr-4": {
    "ChristianGiupponi\\": "app/ChristianGiupponi"
 }
like image 125
Christian Giupponi Avatar answered Jan 31 '23 08:01

Christian Giupponi