0
votes

I'm trying to use PHPMailer through composer.

I'm using namespace and PSR-4 autoloading for my app

My file organisation is like this

-bin
  -controllers
    - Controller.php (namespace bin\controllers)
  -vendor
    -phpmailer
      -phpmailer
       -src
         PHPMailer.php (namespace HPMailer\PHPMailer)

In composer.json, I wrote this

"autoload": {
    "psr-4": {"bin\\vendor\\phpmailer\\": "bin/vendor/phpmailer/phpmailer/src/PHPMailer.php"}
}

But when I use

<?php

namespace bin\controllers;

use bin\vendor\phpmailer\PHPMailer;

abstract class Controller {

    public function __construct()
    {
        $mail = new PHPMailer();
    }
}

I got a fatal error :

require_once(): Failed opening required '/Users/thomas/Library/Mobile Documents/com~apple~CloudDocs/saveProject/bin/../bin/vendor/phpmailer/PHPMailer.php'

How I could configure the namespace to use the class correctly?

Thanks a lot in advance.

1

1 Answers

0
votes

You're mixing up paths and namespaces; for the most part they are independent, but PSR-4 and friends help to map one to the other.

PHPMailer only supports namespaces as of version 6.0, which is not yet released, though you can of course use a pre-release version.

use bin\vendor\phpmailer\PHPMailer;

Should be:

use PHPMailer\PHPMailer\PHPMailer;

The use keyword is used to import an entity from another namespace into the current one - note that this is conceptually different from including a file with include / require.

It looks like you're mixing up namespaces in your own app too - typically you'd use a namespace that's based on a <vendorname>\<projectname> pattern, so your example controller might be :

namespace MyCompany\MyProject;

class MyMailController...

Or you could make use of multiple namespaces within your own project like this:

namespace MyCompany\MyProject\Controllers;

class Mail...

which would define the MyCompany\MyProject\Controllers\Mail class.