We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Adding third party class in autoloading using composer

Hi,

Excuse me for my naive knowledge of OOP as well as phalcon. Here is the thing, there is a class provided by third party. I wanted to add it to phalcon via composer autoload. And then want to wrap it around my class so that if in future I change that third party, I don' thave to tinker lots of code.

I created my class and added to DI:

/**
 * Third Party api 
 */
$di->set('thirdpartyapi', function () {
    return new ThirdPartyApi();
});

I created my own ThirdPartyApi.php and class with same name in it.

Assuming, theirparty class name is "ThirdPartyProvider", I copied it to vender -> thirdpartyprovider ->src and added following its composer.json

This is folder structure under vendor : structure

{
    "name": "thirdpartyprovider/",
    "description": "A third party service",
    "autoload": {
        "psr-4": {
            "ThirdPartyProvier\\": "src/"
        }
    },

    "license": "MIT"
}

Content of ThirdPartyProvder.php


namespace ThirdPartyProvider;

class ThirdPartyProvider
{

    private $username;
    private $hash;
    private $apiKey;

    private $errorReporting = false;
            .
            .
            .
            .
            .
            }

Then I ran 'composer dump' to include autoload

Now if I call ThirdPartyApi.php , it fails to load ThirPartyProvider class. Clearly its not being loaded into my class.

Kindly advice how to add third party classes in phalcon with composr autloader.

Usually I don't bother trying to integrate Composer's autoloader. It works by itself, so just require() it.

When setting up your Phalcon autoloader (in bootstrap.php, or setup.php, or whatever file you define your services in), just include a plain PHP require() call to the Composer autoload file. It won't overwrite the Phalcon autoloader, and should just work.

edited Aug '18

Phalcon Loader method:

$loader->registerFiles([APP_PATH . '/vendor/autoload.php']);

will include composer in case you have registered your lib with composer.

If not, with registerFiles() loader method you can register any PHP file/class.



8.8k

May be I did not explain properly , I had included APP_PATH . '/vendor/autoload.php and it was working for other vendor libraries but I was not able to get ThirdPartyApi.php to load so that I can use ThirPartyApi() class in the application.

Then you have problem with composer and that 3rd party lib, it's not Loader problem.



8.8k

Yes, because that 3rd party lib is only a class and I wanted to add it via composer , thats where I asked for suggestion. May be see my config above and tell me what I missed.