Search code examples
phpcomposer-phppsr-4

Composer autoload doesn't work regardless of whatever I do


I have a project, and I need some packages, so I reorganized the project to use PSR-4.

Here's my composer.json:

{
    "name": "me/production",
    "type": "project",
    "authors": [
        {
            "name": "Me",
            "email": "[email protected]"
        }
    ],

    "config": {
        "platform": {
            "php": "5.6.1"
        }
    },
    "autoload": {
      "psr-4": {
        "API\\": "api/"
      }
    },

    "require": {
        "nesbot/carbon": "^2.25"
    },

}

it doesn't work in my scripts. But, here's the real kicker: I do require_once __DIR__ . '/vendor/autoload.php'; in my php console, and it doesn't work either. I have triple and quadruple checked the path, the autoload is there.

What do I mean by "doesn't work"? the autoload requires successfully. It allows me to use libraries. BUT actual instantiations result in a

Class not found error.

Not only for my classes in the API namespace, which are namespaced in the top of the file and are exactly in the folder they're suppose to be, but I also CANNOT instantiate Carbon. I can use Carbon\Carbon but any attempt to instantiate will fail.

Interestingly, instantiation of \Carbon\Carbon directly does not fail.

What's going on? This is weird.

Thank you in advance.

EDIT: I tried redumping the autoloader, I also tried removing the vendor folder and reinstalling. All to no avail.

EDIT: May be worth mentioning I downgraded carbon to ^1.21 because carbon 2 doesnt support php 5.6. But it still doesn't work.

EDIT: It happens with my API namespace as well, here's an example using my implementation of the Instagram API:

 use \API\Insta;
php > var_dump(new Insta);
PHP Fatal error:  Class 'Insta' not found in php shell code on line 1
php > var_dump(new \API\Insta);
object(API\Insta)#3 (1) {
  ["ig_token"]=>
  string(51) "A_VALID_TOKEN"
}
php > 

EDIT: The problem solved itself, it has now mutated into one I care very little about: I can use everything but not in the php console. I am not sure what fixed it.


Solution

  • As you found out, nesbot/carbon, version 2.25 requires at least PHP v7.1.8.

    Just having a use statement doesn't check anything, instead it creates a local alias that can be used. If you try to use something that does not exist, only then would it fail.

    Please clarify that you have the following directory structure:

    • ./composer.json
    • ./composer.lock
    • ./Api/Insta.php

    and in the file Api/Insta.php:

    namespace API;  // this is your top namespace name
    use Carbon/Carbon; // etc
    class Insta { ... }
    

    Having the namespace different to the directory name can lead to confusion.

    There will also be the index.php/front-controller that pulls in the vendor/autoload.php file and presumably runs the framework.