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

纵饮孤独 提交于 2019-12-11 17:32:48

问题


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!


回答1:


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();


来源:https://stackoverflow.com/questions/52607630/what-is-the-simplest-way-to-use-an-external-php-library-in-a-custom-magento-2-mo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!