PHP使用来自作曲家的自动加载器添加自定义命名空间 [英] PHP adding custom namespace using autoloader from composer

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

问题描述

这是我的文件夹结构:

Classes
  - CronJobs
    - Weather
      - WeatherSite.php

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

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

$loader = include(LIBRARY .'autoload.php');
$loader->add('ClassesWeather',CLASSES .'cronjobs/weather');
$weather = new ClassesWeatherWeatherSite();

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

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 'ClassesWeatherWeatherSite' not found

这是我的 WeatherSite.php 文件:

Here is my WeatherSite.php file:

namespace ClassesWeather;

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

Update your autoload section in composer.json:

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

解释一下:它是 {"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 ClassesWeatherWeatherSite();

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

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