symfony2: how to integrate a php library which is

2019-07-15 00:14发布

问题:

I am trying to integrate Agile CRM in my Symfony2 application.

There is a PHP library provided by Agile : https://github.com/agilecrm/php-api

However it's not a bundle.

How can I integrate it correctly in my application? Should I put a require once in my app.php or my kernel? Or is there a better way?

回答1:

Composer has a feature to auto load files

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

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}

Other ways ?

Expose the functionality as a Service using the code provided in the library.



回答2:

I think the best way to do this is to:

  • contribute to the project to add a composer.json
  • contribute to allow the configuration to be loaded from elsewhere instead of being hardcoded

Then you'll be abled to simply use composer to load that package. :)



回答3:

Composer (as mentioned in other answers) is only a dependency manager and therefore only part of the solution. If you are really interested in the cleanest way, it is quite simple: write the bundle yourself.

In fact, there are many examples of bundles that work as integration layers for 3rd party libraries. For example, look at https://github.com/nelmio/alice, a Symfony2 bundle meant to wrap Faker, an external data fixture lib.

A bundle may declare configuration options overridable by the app main config files. It may expose service definitions for the library objects so that you can avoid to create them manually and inject them when needed (whether or not the library is written with DI in mind). It may be also useful for twig extensions, event listeners and so on.

A good written bundle promotes reuse, testability and separation of concern. Don't be scared from writing your bundle from scratch, start here http://symfony.com/doc/current/cookbook/bundles/best_practices.html



回答4:

As agilecrm/php-api is not available on Packagist the best approach would be to add the repository to your composer.json file and then install the package the same way you would with everything else.

{
    //...
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "agilecrm/php-api",
                "version": "2.1.0",
                "source": {
                    "url": "https://github.com/agilecrm/php-api",
                    "type": "git",
                    "reference": "2.1.0"
                }
            }
        }
    ],
    "require": {
        //...
        "agilecrm/php-api": "2.1.0"
    }
//...
}


回答5:

You should add it to your composer.json

{
        "require": {
            "agilecrm/php-api": "dev-master"
        },
        "repositories": [
        {
            "type": "vcs",
            "url":  "git@github.com:agilecrm/php-api.git"
        }
    ]
}

or you can add it to composer autoloader https://getcomposer.org/doc/01-basic-usage.md#autoloading