Question

How do I autoload a set of library API functions with a composer installed library?

I have a library with a function API used to interface the libraries internal objects and want composer to automatically load the API and make it available after install without requiring the end-developer to include a file.

Currently the library is loaded by just including the __init__.php and it includes the API functions and an autoloader if required.

Thanks!

Was it helpful?

Solution

Composer always will require the end-developer to include one file, which is vendor/autoload.php. You cannot make it easier that that.

But what you can do is make including __init__.php optional because the integration of Composer allows you to use that autoloader instead. This will also work for functions, which could not really be autoloaded - Composer offers to always include a file if being told so.

So in the end your Composer configuration of that API library would look like this:

{
    "name": "yourvendorname/yourfancylibraryname",
    "license": "any open source identifier",
    "autoload": {
        "psr-0": {
            "Foo_Api": "src/files"
        },
        "classmap": [
            "extra/folders_with_any_other_class_not_conforming_to_psr0_or_psr4"
        ],
        "files": [
            "functions/file_with_your_function_definitions.php"
        ]
    }
}

I don't know about whether your classes conform to PSR-0 or even PSR-4, but if they do, you and everyone would benefit if you can declare the autoloader with these standards. If not: Classmap will help you.

Your function definition will be loaded by the file or files mentioned in "files".

You don't need your own autoloader anymore for Composer.

Of course you could also simply mention the old __init__.php as the file to be included in "files", but this would separate your library from all the other classes, would probably be less performant (Composer already has a very good autoloader - there is no need to have two of them) and would definitely exclude all your classes from being dumped into an even faster Composer classmap autoloader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top