douchen5971 2016-10-08 05:52
浏览 179
已采纳

无法从类中加载swiftmailer。 我收到错误:找不到类“Swift_SmtpTransport”

I am implementing a mailing solution where if I call swiftmailer from the main index.php file like :

require_once '../swiftmailer/lib/swift_required.php';
...
$result = $mailer->send($message);

All is great. But when I use the same swiftmailer library in my application class to implement layout/design partition like this:

// File: controller.php

class Index {
      ...
      public function ignition() {
            ...
            spl_autoload_register(array($this, 'myClassLoaderFx'));
      }

      public function myClassLoaderFx($name) {
            $classes = array(
                  'Blah' => '../blah/Blah.php',
                  ...
                  'Swift' => '../swiftmailer/lib/swift_required.php'
            );
            if(!array_key_exists($name, $classes)){
                  die('Class not found');
            }
            require_once $classes[$name];
      }

// File: Mailer.php

class Mailer {
      ...
      public function main($recepient[], $sender, $subject, $body) {
            ...
            $transport = Swift_SmtpTransport::newInstance('xyz.google.com', 465, "ssl")->setUsername($this->username)->setPassword($this->password);
            ...
            $result = $mailer->send($message);
}

Upon execution I get : Class "Swift_SmtpTransport" not found. The library is loaded because I get all Swift class list in the netbeans context help. But, upon execution I get the error. I have done all possible spell checkings. Getting nowhere from here on. Please help.

  • 写回答

1条回答 默认 最新

  • doushao8421 2016-10-08 08:53
    关注

    Looks like your swiftmailer class Swift() is loaded but its incomplete. You can take one of the following approaces to solve this :

    1. Add "extends Swift" to your class declaration in file Mailer.php.

      class Mailer extends Swift {

    Or,

    1. Load the swiftmailer library in a construct() function of Mailer class.

      Remove the following line from myClassLoaderFx() function from controller.php : 'Swift' => '../swiftmailer/lib/swift_required.php'

      And Create a construct for Mailer() class in file Mailer.php public function __construct(){ require_once '../swiftmailer/lib/swift_required.php'; }

    Go with the first approach of using spl_autoload_ function unless you want to keep swiftmailer away from the main application into a managed class. This can come in handy in case you would like to switch to another mailer. You wont have to make changes to controller.php etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)