3

I am getting an Catchable fatal error with Slim 3 on my Models, i have a similar set up on my Controllers and it works just fine. When i implement the same on my Modal class i get the following error.

Catchable fatal error: Argument 1 passed to Base\Models\BaseModel::__construct() must implement interface Interop\Container\ContainerInterface, none given, called in \bootstrap\app.php on line 111 and defined in \Models\BaseModel.php on line 11

This is my bootstrap file

use Noodlehaus\Config;

session_start();

require __DIR__ . '/../vendor/autoload.php';

$app = new App([
    'settings' => [
        'determineRouteBeforeAppMiddleware' => true,
        'displayErrorDetails' => true,
        'addContentLengthHeader' => false
    ],
]);

$container = $app->getContainer();

$container['config'] = function() {
    return new Config(__DIR__ . '/../config/' . file_get_contents(__DIR__ . '/../env.php') . '.php');
};

$container['mailer'] = function($container) {
    return new MailgunEmail; ///LINE 110
};

require __DIR__ . '/../app/routes.php';

This is the env.php

return [
    'mailgun' => [
        'apikey' => 'key-123456',
        'domain' => 'sandbox123456.mailgun.org',
        'from' => 'noreply@anydomain.com',
    ],
];

My Base Model

namespace Base\Models;

use Interop\Container\ContainerInterface;

abstract class BaseModel {

    protected $container;

    public function __construct(ContainerInterface $container) { /// LINE 11
        $this->container = $container;
    }

    public function __get($property) {
        if($this->container->{$property}) {
            return $this->container->{$property};
        }
    }

}

My Email Model

namespace Base\Models;

use Base\Models\BaseModel;
use Http\Adapter\Guzzle6\Client;
use Mailgun\Mailgun;

class MailgunEmail extends BaseModel {

    public function sendWithApi($to, $subject, $html) {
        $client = new Client();
        /// INSTEAD OF HARD CODING LIKE THIS
        $mailgun = new Mailgun('key-123456', $client);
        /// I WANT TO DO SOMETHING LIKE THIS
        $mailgun = new Mailgun($this->config->get('mailgun.apikey'), $client);

        $domain = 'sandbox123456.mailgun.org';

        $builder = $mailgun->MessageBuilder();
        $builder->setFromAddress('noreply@anydomain.com');
        $builder->addToRecipient($to);
        $builder->setSubject($subject);
        $builder->setHtmlBody($html);

        return $mailgun->post("{$domain}/messages", $builder->getMessage());
    }

}

I am not sure why i am getting this error or how i can fix it.

John
  • 111
  • 10

1 Answers1

1

Just pass the $container variable to your MailgunEmail constructor in your bootstrap file.

$container['mailer'] = function($container) {
    return new MailgunEmail($container); ///LINE 110
};
baikho
  • 5,203
  • 4
  • 40
  • 47