Adding Third party library to Laravel

2019-08-25 02:58发布

问题:

I have an RSA algorithm Library giving to me by a payment gateway and When I do a

include (app_path().'/PaymentGateway/Crypt/RSA.php');

this and try to make an object as $rsa = new Crypt_RSA(); this it gives me and error saying

Class 'App\Http\Controllers\Crypt_RSA' not found

I tried including it in web.php and making an object it worked the problem occur when I try to include it in a Controller.

回答1:

You can tell Composer to autoload any (non-PSR) class by adding the base folder to:

"autoload": {
"classmap": [
    "app/commands",
    "app/database/migrations",
    "app/database/seeds",
    "app/tests/TestCase.php"
],
....

And you can also autoload autoloaders by adding them to the files section:

"autoload": {
"files": [
    "temboo/src/Temboo_Loader.php"
],

...

After adding those entries, execute:

composer dumpautoload

And check the file vendor/composer/autoload_classmap.php, the available classes must be all listed in it, if one file is not there it will not be autoloaded.



回答2:

On default, everything included in the app folder of your laravel project is autoloaded, that is described in the composer.json of your project:

...        
"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
...

The only thing you will need to do is simply use the namespace:

use App/Path/To/Third/Party/plugin/Class;

If, however, the plugin is placed outside of the scope of App, then simply add it to the psr-4 autoloader:

    "psr-4": {
        "ProjectRootNs\\": "projects/myproject/"
    }


回答3:

This is what I did. Oh and a little back ground I use to have this in Laravel 4, PHP 5, jpgraph 2.

I am using jpgraph 4.1 on Laravel 5.5 using PHP 7.

  1. Created a folder under app called jpgraph
  2. Placed the src folder that is in the tarball of jpgraph in that folder
  3. Created file call Graph1.php, is my code using jpgraph, with the class Custom_GraphsJM in the jpgraph folder.
  4. In composer.json added "app/jpgraph/Graph1.php" to the "classmap"

    "autoload": {
      "classmap": [
        "database/seeds",
        "database/factories",
        "app/jpgraph/Graph1.php"
      ],
      "psr-4": {
        "App\\": "app/"
      }
    },
    
  5. In the application folder:

    composer dump-autoload

  6. Checked the autoload_classmap.php and I have

    'Custom_GraphsJM' => $baseDir . '/app/jpgraph/Graph1.php',

  7. In my Model at the top I have

    use Custom_GraphsJM;

  8. To create a class

    $Two_Graphs_Temp = new Custom_GraphsJM();