找不到Composer自动加载类 [英] Composer Autoloading classes not found

查看:605
本文介绍了找不到Composer自动加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件夹结构如下:

includes/
  libraries/
    Classes/
      Contact/
        Contact.php
        ContactController.php

admin/
  controllers/
    contact/
      edit.php

Contact.php是我正在尝试使用的该文件的类.该文件包含.

Contact.php is my class that file that I'm trying to use. The file contains.

<?php
namespace Classes;

class Contact {
    function __construct() {
        die('here');
    }
}

我的composer.json文件如下:

I have my composer.json file like:

{
    "autoload": {
        "psr-4": {
            "Classes\\": "includes/libraries/Classes/"
        }
    },
}

我要在其中使用Contact类的文件是admin/controllers/contact/文件夹中的edit.php.我的edit.php文件是这样的:

The file I'm trying to use the Contact class in is edit.php within the admin/controllers/contact/ folder. My edit.php file is like:

<?php

use Classes\Contact;

$contact = new Contact();

var_dump($contact);

此文件包含vendor/autoload.php文件,但是我似乎无法使用该类吗?

This file has the vendor/autoload.php file included, yet I can't seem to get it to use the class?

推荐答案

Classes/Contact/Contact.php和作曲家规则"Classes\\": "includes/libraries/Classes/"暗示Classes\Contact\Contact类,而不是Classes\Contact.

Classes/Contact/Contact.php and the composer rule "Classes\\": "includes/libraries/Classes/" imply Classes\Contact\Contact class, not Classes\Contact.

因此,如果您实际上想要Classes\Contact类,请将Classes/Contact/Contact.php文件移动到父目录:Classes/Contact.php.

So if you actually want Classes\Contact class, move the Classes/Contact/Contact.php file up to the parent directory: Classes/Contact.php.

但是,如果所需的类的名称空间路径为Classes\Contact\Contact,则更改use:

If, however, the desired namespace path to the class is Classes\Contact\Contact, then change the use:

use Classes\Contact\Contact;

namespace:

namespace Classes\Contact;

class Contact {}

示例

├── composer.json
├── includes
│   └── libraries
│       └── Classes
│           └── Contact
│               └── Contact.php
├── test.php
└── vendor
    ├── autoload.php
    └── composer
        ├── autoload_classmap.php
        ├── autoload_namespaces.php
        ├── autoload_psr4.php
        ├── autoload_real.php
        ├── autoload_static.php
        ├── ClassLoader.php
        ├── installed.json
        └── LICENSE

vendor/下的文件由作曲家生成.

The files under vendor/ are generated by composer.

composer.json

{
    "name": "testpsr4",
    "autoload": {
        "psr-4": {
            "Classes\\": "includes/libraries/Classes"
        }
    }
}

test.php

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Classes\Contact\Contact;

$c = new Contact;
$c->test();

包括/库/类/Contact/Contact.php

<?php
namespace Classes\Contact;

class Contact {
    public function test () {
        echo __METHOD__, PHP_EOL;
    }
}

测试

composer update
php test.php

输出

Classes\Contact\Contact::test

这篇关于找不到Composer自动加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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