Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP使用来自composer的autoloader添加自定义命名空间_Php_Namespaces_Composer Php_Autoload - Fatal编程技术网

PHP使用来自composer的autoloader添加自定义命名空间

PHP使用来自composer的autoloader添加自定义命名空间,php,namespaces,composer-php,autoload,Php,Namespaces,Composer Php,Autoload,以下是我的文件夹结构: Classes - CronJobs - Weather - WeatherSite.php 我想从脚本中加载WeatherSite类。Im使用自动加载的composer: $loader = include(LIBRARY .'autoload.php'); $loader->add('Classes\Weather',CLASSES .'cronjobs/weather'); $weather = new Classes\Weather

以下是我的文件夹结构:

Classes
  - CronJobs
    - Weather
      - WeatherSite.php
我想从脚本中加载WeatherSite类。Im使用自动加载的composer:

$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
部分:

"autoload": {
    "psr-4": {
        "Classes\\Weather\\": "Classes/CronJobs/Weather"
    }
}
解释:它是
{“Namespace\\\:“要在“}”中找到的目录

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

然后你可以这样使用它:

include(LIBRARY .'autoload.php');

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

实际上,您不需要定制自动加载器,您可能可以使用PSR-4。您是否使用
composer.json
?如果是这样,你能在
autoload
部分添加它的内容吗?@TomášVotruba我想对于我编写的自定义类,我必须将名称空间添加到composer附带的自动加载脚本中?谢谢,但是我如何引用脚本中的名称空间呢?我是否仍然需要将命名空间类添加到自定义类文件WeatherSite.php的顶部?在调用该类的脚本中,它只是$site\u weather=new Classes\weather\SiteWeather()?不管怎样,我让它工作了,但前提是composer中的命名空间指向php文件所在的子目录。因此,如果composer I拥有它的class=>class/CronJobs,那么在脚本$weather=new Classes\weather\WeatherSite()中;我仍然会得到错误,但是如果我将composer更新为Classes=>class/CronJobs/Weather,它现在就可以工作了。知道我到底做错了什么吗?好吧,看来我知道了。在WeatherSite.php文件中,我将其从名称空间类更改为名称空间类\Weather,现在它可以工作了。谢谢你的帮助。你能确认这是做这种事情的正确方法吗?或者这是一个糟糕的“设计”?对不起,我已经相应地修正了我的答案。您是否尝试过
composer.json
方法?那是正确的。使用
$loader
是一种糟糕的做法。“composer dump autoload”对我不起作用,但“php artisan optimize”对我起作用。