【问题标题】:PHP adding custom namespace using autoloader from composerPHP使用来自作曲家的自动加载器添加自定义命名空间
【发布时间】:2015-10-08 21:30:06
【问题描述】:

这是我的文件夹结构:

Classes
  - CronJobs
    - Weather
      - WeatherSite.php

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

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

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

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

这是我的 WeatherSite.php 文件:

namespace Classes\Weather;

class WeatherSite {

    public function __construct()
    {

    }

    public function findWeatherSites()
    {

    }

}

我做错了什么?

【问题讨论】:

  • 您实际上不需要自定义自动加载器,您可能可以使用 PSR-4。你用composer.json吗?如果是这样,您可以将其内容添加到autoload 部分吗?
  • @Tomáš Votruba 我认为对于我编写的自定义类,我必须将命名空间添加到 composer 附带的自动加载器脚本中?

标签: php namespaces composer-php autoload


【解决方案1】:

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

composer.json 中更新您的autoload 部分:

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

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

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

那么你可以这样使用它:

include(LIBRARY .'autoload.php');

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

【讨论】:

  • 谢谢,但是我如何引用脚本中的命名空间呢?我还需要将命名空间类添加到我的自定义类文件 WeatherSite.php 的顶部吗?在调用该类的脚本中只是 $site_weather = new Classes\Weather\SiteWeather()?
  • 没关系,我让它工作,但前提是作曲家中的命名空间指向 php 文件所在的子目录。所以如果作曲家我有它 Classes => class/CronJobs 然后在脚本 $weather = new Classes\Weather\WeatherSite();我仍然收到错误消息,但是如果我将作曲家更新为 Classes => class/CronJobs/Weather,它现在可以工作了。知道我还在做什么错吗?
  • 好吧,看来我想通了。在 WeatherSite.php 文件中,我将其从命名空间 Classes 更改为命名空间 Classes\Weather,现在它可以工作了。谢谢你的帮助。你能确认这是做这样的事情的正确方法吗?或者这是一个糟糕的“设计”?
  • 对不起,我已经相应地修正了我的答案。你试过composer.json的方式吗?那是正确的。使用$loader 是不好的做法。
  • 'composer dump-autoload' 对我不起作用,但 'php artisan optimize' 对我有用。
猜你喜欢
  • 2018-08-30
  • 2013-08-11
  • 2018-05-07
  • 2013-04-08
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多