How can I automatically load a custom class in Laravel 5.1?

I created a library folder in the app folder to add my own classes.

enter image description here

This is the contents of the app/library/helper.php :

 <?php namespace Library; class MyHelper { public function v($arr) { var_dump($arr); } } 

I added a namespace in composer.json :

enter image description here

and then I ran

 $ composer dump-autoload 

but it does not seem to have any effects.

Files

  • vendor/composer/autoload_psr4.php
  • vendor/composer/autoload_classmap.php

did not change.

If I try to create an instance of MyHelper , Laravel reports the following error:

enter image description here

I'm not sure what I'm doing wrong.

+4
source share
4 answers

Your startup configuration is almost good, but you have

  • invalid namespaces
  • Wrong Way

To fix the problem, configure the startup configuration:

 { "autoload": { "classmap": [ "database" ], "psr-4": { "App\\": "app/" } } } 

Then rename the /library directory to /library (note the case).

Then rename the file /app/Library/helper.php to /app/Library/MyHelper.php (note how the class name should match the file name).

Then edit the namespace of the class provided by /app/Library/MyHelper to match the PSR-4 prefix (and therefore the structure of your project), as well as the class’s customs:

 namespace App\Library; class MyHelper { public function v($arr) { var_dump($arr); } } 

For reference see:

+3
source

Use the files directive in composer.json : https://getcomposer.org/doc/04-schema.md#files

 { "autoload": { "files": ["app/library/helper.php"] } } 
0
source

I know this question was answered some time ago, but the reason it does not work is because you need to provide a namespace that matches the file structure. Therefore, since the Library class is inside the App folder, you need to:

 namespace App\Library; class MyHelper{ public function v($arr){ var_dump($arr); } } 

In addition, if you intend to call the MyHelper class, you need to call the MyHelper.php file

0
source

Use composer .json:

  "autoload": { "classmap": [ "database", "app/Transformers" ] }, 

Add your automatic download directories, for example, I added the application / Transformers.

Remember to add run composer dump-autoload .

The only problem with this method is that you need to run composer dump-autoload whenever you add a new class to this directory.

Or you can use the "Files" in composer.json.

 "autoload": { "files": ["src/MyLibrary/functions.php"] } 
-one
source

All Articles