Autoloader resulting in class not found

强颜欢笑 提交于 2019-12-04 17:54:14

Yes, indeed, composer should take care of your dependencies and autoloading. Your configuration also is correct. Let's walk through a check list:

Does your environment look like this?

$ tree
.
├── composer.json
├── composer.phar
├── index.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
└── wp-content
    └── plugins
        └── example-plugin
            └── Classes
                └── MyService.php

Does your composer.json look like this?

$ cat composer.json
{
    "name": "my/project",
    "authors": [
        {
            "name": "My Name",
            "email": "my@na.me"
        }
    ],
    "autoload": {
       "psr-4": {
           "Classes\\": "wp-content/plugins/example-plugin/Classes"
       }
    },
    "require": {}
}

Does your implementation look like this?

$ cat wp-content/plugins/example-plugin/Classes/MyService.php
<?php
namespace Classes;

class MyService {
}

Finally, does your index look like this?

$ cat index.php
<?php

require_once('./vendor/autoload.php');

$foo = new \Classes\MyService;

var_dump($foo);

If your answer is "Yes" to all of these, have you refreshed your autoloader?

$ composer dump-autoload

If your answer is "Yes", then create a new directory, download composer.phar, run php composer.phar init, copy and paste this answer's files into that directory, and try again.

If that works, then diff this with your implementation. My guess is, if you get this far, you have a stray character -- possibly Unicode white space -- hiding in one of your files.

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