Search code examples
phpsymfonymandrillphp-7.2

Using a library in Symfony


Im trying to use the Mandrill API with the Symfony framework. I installed the API using composer (composer require mandrill/mandrill). This places the library in the /vendor directory but Im having trouble actually using the Mandrill class in my service.

<?php

namespace App\Services;

use App\Services\Utilities;

class Email {

    public function __construct($mandrill_api_key, Utilities $u){

        $mandrill = new Mandrill($this->mandrill_api_key); // throws exception
    }
}

The error I get is as follows: "Attempted to load class "Mandrill" from namespace "App\Services". Did you forget a "use" statement for another namespace?"

Obviously, its trying to load the Mandrill class from the Services namespace. But I need that namespace to load the Utilities service.

I tried adding the line use Mandrill\Mandrill - to load that mandrill class from the mandrill directory in vendor, but this throws the same namespace error but for the Mandrill namespace.

The API documentation has the following:

<?php
    require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
    $mandrill = new Mandrill('YOUR_API_KEY');
?>

require_once is how I included this class previously in php 5.x but I not able to include it in symfony/php 7.x


Solution

  • If you want to access a classname from the root namespace you need to prepend it with a backslash:

    new \Mandrill(...)
    

    References: