Composer psr-4 autoload issue

ε祈祈猫儿з 提交于 2021-02-07 08:26:40

问题


I have problem with autoloading with composer when i use psr-4 autoloading it doesn't work and give me error.

I tried:

$ composer dump-autoload

and a lot of other thing but it doesn't work without

require one;

error:

You are now a master builder, that knows how to autoload with a 
classmap! 
Fatal error: Uncaught Error: Class 'VegithemesLibraryGreeting' not 
found in /home/vaclav/Server/vssk/VSSK/project/aldemo/index.php:10 
Stack trace: #0 {main} thrown in 
/home/vaclav/Server/vssk/VSSK/project/aldemo/index.php on line 10

composer.json:

{
"autoload": {
    "files": ["mylibrary/functions.php"],

    "classmap": [
    "classmap"
    ],

    "psr-4": {
        "one\\": "src/"
    }
  }
}

greeting.php (file with class to load):

<?php
namespace one;

Class Greeting
{
    public function hi()
    {
        return "We got you covered";
    }
}

index.php file:

<?php

require 'vendor/autoload.php';

echo lego();

$cm = new Cmautoload;
echo $cm->classmap();

$vt = new oneGreeting;

echo $vt->hi();

回答1:


It is generally good practice to capitalize the first letter of a class name. It also adheres with the rules of PSR-1.

Change your composer.json file to look like this:

{
"autoload": {
    "files": [
        "mylibrary/functions.php"
    ],

    "classmap": [
        "classmap"
    ],

    "psr-4": {
        "One\\": "src/"
    }
  }
}

Now, in your index file. We are going to import the autoloader. To do this simply require it:

require 'vendor/autoload.php';

Now that you have included the autoloader, go into every class and set the namespace.

The classes in your src/ == namespace One;

Check your classes in src/ and make sure they are all namespaced. Meaning that they should all have the following line of code at the top:

namespace One;

As mentioned before, update your file names to Foo.php and class names to class Foo to adhere to PSR. (This is not required but highly recommended and standard procedure.)

To use one of your classes you would say use One\Greeting;

$greeting = new Greeting();
echo $greeting->hi(); //"We got you covered"



回答2:


I found the problem, there was missing:

use One\Greeting; 

In a lot of tutorials there isn't a word about it.




回答3:


Another relevant detail about this is the namespace must match with the folder structure. If not it will throw the warning.




回答4:


In my case the filename was

src/One/GreetingClass.php

but the class name was in lowercase, causing this error:

class Greetingclass {

Changing the class declaration as GreetingClass fixed the issue.



来源:https://stackoverflow.com/questions/48795183/composer-psr-4-autoload-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!