Reputation: 127
I had a problem importing libraries into the Laravel project. I want to use the image_QRCode-0.1.3 library coded in php used in Project Laravel.
https://pear.php.net/package/Image_QRCode/download
but when I use the require command in class QRCodeController
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
require_once "../../../Library/Image_QRCode-0.1.3/Image_QRCode-0.1.3/Image/QRCode.php";
class QRCodeController extends Controller {
public function genQRCode()
{
$QR = new \Image_QRCode();
$option = array(
'module_size' => 4,
'image_type' => 'png',
'output_type' => 'display',
'error_correct' => 'H',
);
$qrcode = $QR->makeCode(htmlspecialchars("https://blog.shnr.net/?p=526", ENT_QUOTES), $option);
}
}
The program did not run and reported an error.
Please help me, thanks you so much !
Upvotes: 4
Views: 11465
Reputation: 881
To use external classes or any other PHP library into your Laravel project, you have to do the following steps:
1. Create a folder somewhere in your Laravel app that will contain the PHP files you're going to use:
For example you have a custom class, create a folder in the directory app/libraries
. Inside app/libraries
, paste the PHP files you'll be using (the library files you've downloaded).
2. In your composer.json
file, add the folder/directory into your autoload classmap:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/libraries", <------------------ YOUR CUSTOM DIRECTORY
"app/database/migrations",
"app/database/seeds",
]
}
3. Once you're done, just run composer dump-autoload
and you should be able to call your class as follows:
Assuming your class name is SomeClass.php
and it's inside the app/libraries
directory and you're properly namespaced the class you've just copied over, you can now use SomeClass.php
anywhere you need it.
$class = new \some_class_namespace\SomeClass();
You can also give it an alias in your config/app.php
file:
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
....
'SomeAlias' => 'app\libraries\SomeClass',
....
],
After then you can instantiate the class from anywhere in your application just like any other classes:
$class = new SomeAlias();
Upvotes: 11