Composer Autoloading classes not found

后端 未结 1 2050
执念已碎
执念已碎 2021-02-05 22:04

I have folder structure like:

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

admin/
  controllers/
    con         


        
1条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 22:13

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

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

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

    use Classes\Contact\Contact;
    

    And the namespace:

    namespace Classes\Contact;
    
    class Contact {}
    

    Example

    ├── 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
    

    The files under vendor/ are generated by composer.

    composer.json

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

    test.php

    test();
    

    includes/libraries/Classes/Contact/Contact.php

    Testing

    composer update
    php test.php
    

    Output

    Classes\Contact\Contact::test
    

    0 讨论(0)
提交回复
热议问题