Eray
Eray

Reputation: 7128

Composer autoloading vendor classes

I have 2 packages on Packagist.

https://packagist.org/packages/erayalakese/envato-market-api (A) https://packagist.org/packages/erayalakese/envato-update-checker (B)

B requires A.

Now I'm using B package on my projects. But I'm getting Class 'erayalakese\Envato_Update_Checker' (package B) not found error.

This is my composer.json file

{
    "name": "",
    "description": "",
    "require": {
        "erayalakese/envato-update-checker": "^1.3"
    },
    "authors": ...
}

And my project file:

<?php
require_once(__DIR__.'/vendor/autoload.php');
new erayalakese\Envato_Update_Checker(...);

When I add this to my composer.json as temporary solution, it's working :

"autoload": {
    "classmap": ["vendor/"]
}

But I'm not sure I really need to add vendor folder to autoload . I was expecting it will autoload my vendors automatically.

Can you tell me what's I'm missing?

Upvotes: 4

Views: 3813

Answers (1)

Jens A. Koch
Jens A. Koch

Reputation: 41747

You have to change the composer.json of both packages.

Both packages need to define a autoload section.

Referencing: https://getcomposer.org/doc/04-schema.md#classmap


erayalakese/envato-market-api

https://github.com/erayalakese/envato-market-api/blob/master/composer.json

{
    "name": "erayalakese/envato-market-api",
    "description": "Envato Market API to verify and download Envato purchases",
    "authors": [
        {
            "name": "Eray Alakese",
            "email": "[email protected]"
        }
    ],
    "require": {},
    "license": "GPL v2",
    "autoload": {
        "classmap": ["Envato_Market_API.php"]
    }
}

Now this package has a autoload classmap definition, which consists of one PHP file. When you composer install, the autoload definition of the package will be added to the Composer Autoloader.

Same game for the other package:

erayalakese/envato-update-checker https://github.com/erayalakese/envato-update-checker/blob/master/composer.json

{
    "name": "erayalakese/envato-update-checker",
    "description": "Checks Envato WordPress plugins' updates and download its if any update available",
    "require": {
        "erayalakese/envato-market-api": "^1.0"
    },
    "authors": [
        {
            "name": "Eray Alakese",
            "email": "[email protected]"
        }
    ],
    "license": "GPL v2",
    "autoload": {
        "classmap": ["Envato_Update_Checker.php"]
    }
}

In your main project:

  • require the "updater" package in the composer.json of your main project
    • the updater packages included the api package via it's require section (so you get both)
  • add require_once(__DIR__ . '/vendor/autoload.php'); to the project bootstrap
  • enjoy Class via Composers Autoloader: new erayalakese\Envato_Update_Checker(...);

Remove this line:

https://github.com/erayalakese/envato-update-checker/blob/master/Envato_Update_Checker.php#L11

Upvotes: 2

Related Questions