Home > Software design >  php laravel how to include additional library after it was installed with composer
php laravel how to include additional library after it was installed with composer

Time:09-16

In a php laravel 9 project i try to use this library:

https://packagist.org/packages/cnlpete/image-metadata-parser

I added it to composer configuration:

composer require cnlpete/image-metadata-parser

Then I add it in controller to be able to find the class.

I tried like this :

//add this into controller:
require '../vendor/autoload.php';
use cnlpete\image-metadata-parser;

And I get error syntax error, unexpected token "-", expecting "," or ";"

Then I also added in config/app.php this:

'aliases' => [

       'ImageMetadataParser' => cnlpete\image-metadata-parser\imageMetadataParser::class,
  ],  

I see the path to the library after it was installed by composer is: myappname/vendor/cnlpete/image-metadata-parser/imageMetadataParser.php

If I use just like this without other configuration:

$imageparser = new vendor\cnlpete\image-metadata-parser\ImageMetadataParser(....);

I get error: Error Class "App\Http\Controllers\vendor\cnlpete\image" not found

How to include this library in the controller to be able to use it?

CodePudding user response:

The class doesn't have a namespace. You don't need to import or alias the class. Composer makes it usable project-wide.

Simply use it as if it were imported:

$imageparser = new ImageMetadataParser('file');

Since you're in Laravel, you also don't need to require the autoload.php file a second time.

CodePudding user response:

Your system loads imageMetadataParser.php in

App\Http\Controllers\vendor\cnlpete\image
    ^^^^^^^^^^^^^^^^  ^^^^

Define path as

base_path().'./vendor/autoload.php'; 
or
base_path('./vendor/autoload.php');

base_path() refers to the project root.


Or load it as a custom library.

  1. Creating Your Own Laravel Custom Package: A Step-by-Step Guide
  2. Custom Laravel Packages
  • Related