Composer PSR-4自动加载问题 [英] Composer psr-4 autoload issue

查看:102
本文介绍了Composer PSR-4自动加载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用psr-4自动加载时,使用composer自动加载时遇到问题,它无法正常工作并给我错误.

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

我尝试过:

$ composer dump-autoload

还有很多其他事情,但是如果没有

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

require one;

错误:

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:

composer.json:

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

    "classmap": [
    "classmap"
    ],

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

greeting.php(带有要加载的类的文件):

greeting.php (file with class to load):

<?php
namespace one;

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

index.php文件:

index.php file:

<?php

require 'vendor/autoload.php';

echo lego();

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

$vt = new oneGreeting;

echo $vt->hi();

推荐答案

通常最好将类名的首字母大写.它还遵守 PSR-1 的规则.

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

更改您的composer.json文件,使其看起来像这样:

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:

需要'vendor/autoload.php';

现在您已经包含了自动加载器,进入每个类并设置名称空间.

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

src/中的类== 命名空间One;

src/中检查您的类,并确保它们都已命名空间.这意味着它们都应该在顶部具有以下代码行:

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:

命名空间一个;

如前所述,将文件名更新为 Foo.php ,并将类名更新为 Foo 类遵守PSR.(这不是必需的,但强烈建议您使用标准步骤.)

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.)

要使用您的一个课程,您会说使用One \ Greeting;

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

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

这篇关于Composer PSR-4自动加载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆