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();
相关文章