简体   繁体   中英

having trouble psr-4 autoloading in Laravel

Okay so I have an project folder inside my Laravel app. named TLGD (the name if my site). Inside i created a form validation helper which is being used to take away unnecessary code form the controller.

here is the folder structure:

TGLD\Validation\Forms

and inside here I have my form helper classes

now in the controller just to test it out I was calling the classes by the use methd from php like so:

use TGLD\Validation\Forms\Login;

login being the class for the login validation

now thus works great so I tried to autoload the TGLD folder so I don't need to add the use line in every controller. Here is my composer.json file

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

but when I autoload it it gives me the error that my login class doesn't exist which means the autoloader is not working. Is there a syntax error or am I missing something? I ran

composer dump-autoload -o

well any advice is helpful thank you in advance

What you want to do cannot be done.

You have to use the complete namespace somewhere to identify the class you want to use. You have several options to do this

  1. Using the fully qualified name of the class with namespace like this: new \\TGLD\\Validation\\Forms\\Login() .
  2. Using a use clause that imports the named class into the current namespace for this file with use TGLD\\Validation\\Forms\\Login; ... new Login(); use TGLD\\Validation\\Forms\\Login; ... new Login();
  3. Using a part of the namespace in the use , and use the rest in the class name: use TGLD\\Validation\\Forms; ... new Forms\\Login(); use TGLD\\Validation\\Forms; ... new Forms\\Login();

After you have chosen the class name in one way or the other, PHP knows which class it needs, and then triggers the autoloading if the class is still unknown to PHP.

So you cannot affect the naming of classes with autoloading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM