haydar
haydar

Reputation: 111

What is the simplest way to use an external php library in a custom magento 2 module?

I am new on magento I am currently working on a custom module for magento2 and I want to use an external php library (PHPMailer) within a Block file.

my project files structure:

ModuleFolder
---etc
.
.
---Block
------- Main.php
---lib
------- PHPMailer
.
.

I tried to include the PHPMailer class within my block main.php using:

require_once(__DIR__."/../lib/PHPMailer/src/PHPMailer.php");

and for the class declaration i used :

$mail = new PHPMailer();

also i tried to include the PHPMailer library in the Block folder and nothing works

it always returns :

PHPMailer class is not found in /...../Block/Main.php

And when i tried to put the PHPMailer.php directly in the Block folder like this:

---Block
-----Main.php
-----PHPMailer.php

and included

require_once(__DIR__."/PHPMailer.php");

it returns: cannot declare PHPMailer class in Main.php because the name is already in use in PHPMailer.php

I installed the latest version of PHPMailer from github: https://github.com/PHPMailer/PHPMailer

And i decided to use it because it is so easy and straightforward.

So how can i use this library and what is the best way for this ?

Thanks!

Upvotes: 0

Views: 2043

Answers (1)

scrowler
scrowler

Reputation: 24406

Magento 2 is built with Composer as a first class citizen. You should use Composer to install PHPMailer as well: https://github.com/PHPMailer/PHPMailer#installation--loading

composer require phpmailer/phpmailer

This means the PHPMailer class autoloading is taken care of by Composer, and you can use it immediately in your project code:

$mail = new \PHPMailer\PHPMailer\PHPMailer();

Upvotes: 2

Related Questions