PHPMailer in Codegniter 4.0.0



我正在尝试调用我的库"Phpmailer";在控制器中。我知道有一个框架库来执行这项任务,但我仍然更喜欢PHPMailer。我遵循了3.0.0版本中关于将库集成到框架的教程,显然这会产生一些冲突。如何在Codeigniter 4.0.0中调用我的PHPMailer库?

教程:https://www.codexworld.com/codeigniter-send-email-using-phpmailer-gmail-smtp/

我的图书馆:

<?php
namespace AppLibraries;
use CodeIgniterLibraries; 
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
defined('BASEPATH') or exit('No direct script access allowed');
class Phpmailer {
public function load(){
require_once APPPATH.'ThirdParty/PHPMailer/Exception.php';
require_once APPPATH.'ThirdParty/PHPMailer/PHPMailer.php';
require_once APPPATH.'ThirdParty/PHPMailer/SMTP.php';

$mail = new PHPMailer;
return $mail;
}
}

我的控制器:

<?php
namespace AppControllers;
use CodeIgniterController;
use AppLibrariesPhpmailer;
class Retrieve{
public function send($email){
$this->load->library('phpmailer'); //line 10
$mail = $this->phpmailer->load();

// SMTP configuration
[...]
}
}

检索函数ienter图像描述被另一个方法调用,因此它正在工作。问题是我的库没有加载。我得到以下错误:

ErrorException
未定义的属性:App_ControllersRetrieve:$load
APPPATH/Controllers_Retrieve.php:10-CodeIgniter_Debug_Exceptions->错误处理程序

[1]:https://i.stack.imgur.com/O49B7.png
[2]:https://i.stack.imgur.com/xUUIQ.png

错误本身很简单,但我怀疑背后有更大的问题。

未定义的属性:App_ControllersRetrieve:$load

这不是名称空间问题,您正试图访问不存在的内容。

$this->load-> ... //line 10正试图访问$this(控制器(的属性load,但据您所示,该属性并不存在。

没有真正的单行修复。你试图如何将库"加载"到控制器中并不是你想要做的(查看CI4中的Services类,我想这就是你的想象(。

在我看来,这是最简单的方法:

给库一个构造函数。在其中创建/存储PHPMailer对象,并包含向Library本身发送电子邮件的工作。例如:

<?php
namespace AppLibraries;
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
defined('BASEPATH') or exit('No direct script access allowed');
class Phpmailer {
private $mailer;
function __construct(){
$mailer = new PHPMailerPHPMailerPHPMailer();
}
//Example - do some work
public function send(){


// SMTP configuration
...
if ($this->mailer->send())
{
...
}
}
...
}

这里需要注意的是:如果你不更改库的名称,你可能不得不通过其完整的命名空间引用实际的PHPMailer:例如new PHPMailerPHPMailerPHPMailer();

然后,只要控制器需要库来完成工作,它就可以创建库的一个新实例。

<?php
namespace AppControllers;
use AppLibrariesPhpmailer;
class Retrieve extends BaseController {
public function send($email){
$mailLibrary = new Phpmailer();
$mailLibrary->send();
}
}

与其直接使用use来点燃CodeIgniter\Controller,不如使用控制器类extendBaseController。然后,如果您需要向Controllers的父类添加内容,那么您就不会接触框架的"系统"文件。

如果该库是您一直想要的,那么您可以将其作为控制器的类属性,并在构造控制器本身时创建它,这样它就一直存在。

这假设您已经获得了实际的PHPMailer,并且CI框架正在自动加载。如果你还没有通过Composer安装CI/PHPMailer,我会认真建议你把你的项目转移到以前的安装。这样做将为您的项目节省终身的技术债务,并使命名变得更加容易。

最新更新