5

I want to add custom php API library under vendor folder and I have added the following folder and files under vendor folder.

  1. magento2_root>vendor/abc/
  2. magento2_root>vendor/abc/abc_php/
  3. magento2_root>vendor/abc/abc_php/composer.json
  4. magento2_root>vendor/abc/abc_php/lib/
  5. magento2_root>vendor/abc/abc_php/lib/Test.php

magento2_root>vendor/abc/abc_php/composer.json

{
    "name": "abc/abc_php",
    "type": "library",
    "description": "ABC PHP Client Library",
    "license": "MIT",
    "authors": [
        {
            "name": "Custom Author",
        }
    ],
    "require": {
        "php": ">=5.4.0"
    },
    "autoload": {
        "psr-4": {
            "CustomApi\\": "lib"
        }
    }
}

magento2_root>vendor/abc/abc_php/lib/Test.php

<?php
    

namespace CustomApi;

class Test
{
    public function customMethod(){
    return "abc";
    }
}

When I include this in constructor like following

public function __construct(
...
\CustomApi\Test $testApi,
...
){
// do some logic
}

It gives me Class CustomApi\Test does not exist error.

PS : I have recompiled the composer by using composer dumpautoload command. It does not generate autoload script in autoload_psr4.php under vendor/composer folder.

Can anyone tell me that what I did wrong ? Any suggestion would be appreciated.

Thanks

1 Answer 1

4

After digging whole day continuously, finally I found the solution.

Solution 1 : Add you custom library folder in magento root composer.json like mention below

"autoload": {
        "psr-4": {
            "Magento\\Framework\\": "lib/internal/Magento/Framework/",
            "Magento\\Setup\\": "setup/src/Magento/Setup/",
            "Magento\\": "app/code/Magento/",
            "CustomApi\\": "abc/abc_php/lib" my custom library code
        },
        "psr-0": {
            "": [
                "app/code/"
            ]
        },
        "files": [
            "app/etc/NonComposerComponentRegistration.php"
        ],
        "exclude-from-classmap": [
            "**/dev/**",
            "**/update/**",
            "**/Test/**"
        ]
    },

And recompile the composer by using composer dumpautoload

Solution 2 : Using Packagist. Process is given below

  1. Add your library code to git repository and release.
  2. Add this repository code to http://packagist.org/
  3. install this library via composer directly by command composer require abc/abc_php "1.0.0"

For example, You can check with braintree on git and braintree on packagist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.