我的Models
上的Slim 3收到了一个致命的致命错误,我在Controllers
上设置了类似的设置,它运行正常。当我在Modal class
上实现相同的内容时,我会收到以下错误。
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
这是我的引导程序文件
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';
这是env.php
return [
'mailgun' => [
'apikey' => 'key-123456',
'domain' => 'sandbox123456.mailgun.org',
'from' => 'noreply@anydomain.com',
],
];
我的基本模型
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};
}
}
}
我的电子邮件模型
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());
}
}
我不知道为什么我会收到此错误或我如何解决它。
答案 0 :(得分:1)
只需将$container
变量传递给引导程序文件中的MailgunEmail
构造函数即可。
$container['mailer'] = function($container) {
return new MailgunEmail($container); ///LINE 110
};