尝试使用作曲家自动加载wordpress插件时“找不到类”
I'm writing a plugin and trying to use composer to auto load my classes, but I'm unable to get it working. I know there are a lot of questions on this topic but nothing seems to work for me.
directory structure:
-
plugin-name
- classes
- Class_Name.php
- vendor
- plugin-name.php
- composer.json
- composer.lock
- classes
composer.json file:
{
"require": {
"katzgrau/klogger": "dev-master"
},
"autoload": {
"psr-4": { "Foo\\": "classes" }
}
}
plugin-name.php file:
namespace Plugins_Main;
use Foo\Class_Name;
require 'vendor/autoload.php';
class Plugin_Name_Bootstrap{
public static function run() {
Class_Name::instance();
}
}
add_action('plugins_loaded', array('Plugins_Main\Plugin_Name_Bootstrap', 'run'));
Class_Name.php file:
namespace Foo;
class Class_Name{
protected static $_instance = null;
public static function instance(){
if ( self::$_instance === null ) {
self::$_instance = new self();
}
return self::$_instance;
}
}
According to the docs this autoloading should work, but I'm still getting
Class 'Foo\Class_Name' not found
I thought maybe it related somehow to the fact that I'm trying to initialize "Class_Name" in plugins_loaded hook, But why would that matter if I'm require vendor/autoload.php much earlier?
我正在编写插件并尝试使用composer自动加载我的类,但我无法获得 它工作。 我知道关于这个主题有很多问题,但似乎没有什么对我有用。 p>
目录结构: p>
- 插件名称 p>
- 类
- Class_Name.php LI> UL> LI >
- 供应商 LI>
- 插件-name.php LI>
- composer.json LI>
- composer.lock LI> \ n ul> li>
ul>
composer.json strong>文件: p>
{\ n“require”:{ “katzgrau / klogger”:“dev-master” }, “autoload”:{ “psr-4”:{“Foo \\”:“classes”} \ n} } code> pre>
plugin-name.php strong>文件: p>
namespace Plugins_Main; use Foo \ Class_Name; require'porpors / autoload.php'; class Plugin_Name_Bootstrap { public static function run(){ Class_Name :: instance(); } } add_action('plugins_loaded',array('Plugins_Main \ Plugin_Name_Bootstrap','run')); code> pre>
Class_Name.php strong > file: p>
namespace Foo; class Class_Name { protected static $ _instance = null; public static function instance(){ if(self :: $ _ instance === null){ self :: $ _ instance = new self(); } \ n 返回self :: $ _ instance; } } code> pre>
根据文档,这个自动加载应该有效,但我还是得到了 p>
未找到类'Foo \ Class_Name' p> blockquote>
我认为它可能与某种事实有关 我试图在plugins_loaded钩子中初始化“Class_Name”,但是如果我之前需要vendor / autoload.php那么为什么会这么重要? p> div>
- 类
Needed to require autoload.php with __DIR__
:
from
require 'vendor/autoload.php';
to
require __DIR__ . '/vendor/autoload.php';
Thanks Damian Dziaduch for the answer.