PHP 使用 Composer 中的自动加载器添加自定义命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31504980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:28:20  来源:igfitidea点击:

PHP adding custom namespace using autoloader from composer

phpnamespacescomposer-phpautoload

提问by John

Here is my folder structure:

这是我的文件夹结构:

Classes
  - CronJobs
    - Weather
      - WeatherSite.php

I want to load WeatherSite class from my script. Im using composer with autoload:

我想从我的脚本中加载 WeatherSite 类。我使用带自动加载的作曲家:

$loader = include(LIBRARY .'autoload.php');
$loader->add('Classes\Weather',CLASSES .'cronjobs/weather');
$weather = new Classes\Weather\WeatherSite();

Im assuming the above code is adding the namespace and the path that namespace resolves to. But when the page loads I always get this error:

我假设上面的代码正在添加命名空间和命名空间解析到的路径。但是当页面加载时,我总是收到这个错误:

 Fatal error: Class 'Classes\Weather\WeatherSite' not found

Here is my WeatherSite.php file:

这是我的 WeatherSite.php 文件:

namespace Classes\Weather;

class WeatherSite {

    public function __construct()
    {

    }

    public function findWeatherSites()
    {

    }

}

What am I doing wrong?

我究竟做错了什么?

回答by Tomá? Votruba

You actually don't need custom autoloader, you can use PSR-4.

您实际上不需要自定义自动加载器,您可以使用 PSR-4。

Update your autoloadsection in composer.json:

更新您的autoload部分composer.json

"autoload": {
    "psr-4": {
        "Classes\Weather\": "Classes/CronJobs/Weather"
    }
}

To explain: it's {"Namespace\\": "directory to be found in"}

解释一下:它是 {"Namespace\\": "directory to be found in"}

Don't forget to run composer dump-autoloadto update Composer cache.

不要忘记运行composer dump-autoload以更新 Composer 缓存。

Then you can use it like this:

然后你可以像这样使用它:

include(LIBRARY .'autoload.php');

$weather = new Classes\Weather\WeatherSite();