Composer Autoloading classes not found

我们两清 提交于 2019-12-03 06:07:13

Classes/Contact/Contact.php and the composer rule "Classes\\": "includes/libraries/Classes/" imply Classes\Contact\Contact class, not Classes\Contact.

So if you actually want Classes\Contact class, move the Classes/Contact/Contact.php file up to the parent directory: Classes/Contact.php.

If, however, the desired namespace path to the class is Classes\Contact\Contact, then change the use:

use Classes\Contact\Contact;

And the namespace:

namespace Classes\Contact;

class Contact {}

Example

├── composer.json
├── includes
│   └── libraries
│       └── Classes
│           └── Contact
│               └── Contact.php
├── test.php
└── vendor
    ├── autoload.php
    └── composer
        ├── autoload_classmap.php
        ├── autoload_namespaces.php
        ├── autoload_psr4.php
        ├── autoload_real.php
        ├── autoload_static.php
        ├── ClassLoader.php
        ├── installed.json
        └── LICENSE

The files under vendor/ are generated by composer.

composer.json

{
    "name": "testpsr4",
    "autoload": {
        "psr-4": {
            "Classes\\": "includes/libraries/Classes"
        }
    }
}

test.php

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Classes\Contact\Contact;

$c = new Contact;
$c->test();

includes/libraries/Classes/Contact/Contact.php

<?php
namespace Classes\Contact;

class Contact {
    public function test () {
        echo __METHOD__, PHP_EOL;
    }
}

Testing

composer update
php test.php

Output

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