PHP使用Composer的自动加载器添加自定义名称空间 [英] PHP adding custom namespace using autoloader from composer

查看:235
本文介绍了PHP使用Composer的自动加载器添加自定义名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文件夹结构:

Classes
  - CronJobs
    - Weather
      - WeatherSite.php

我想从脚本中加载WeatherSite类.我在自动加载中使用composer:

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

$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

这是我的WeatherSite.php文件:

Here is my WeatherSite.php file:

namespace Classes\Weather;

class WeatherSite {

    public function __construct()
    {

    }

    public function findWeatherSites()
    {

    }

}

我在做什么错了?

推荐答案

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

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

更新composer.json中的autoload部分:

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

要说明:它是{"Namespace \\":要在其中找到的目录"}

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

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

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

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

Then you can use it like this:

include(LIBRARY .'autoload.php');

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

这篇关于PHP使用Composer的自动加载器添加自定义名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆