简体   繁体   中英

Composer psr-4 autoload issue

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();

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"

I found the problem, there was missing:

use One\Greeting; 

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

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

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.

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