Can't pass class instance to constructor

给你一囗甜甜゛ 提交于 2019-12-05 19:20:25

Eloquent (re)creates itself internally by calling:

new static

An example is in creating a new query:

return with(new static)->newQuery();

I'm not sure if automatic dependency resolution would work in this case, it should always work inside laravel, but as it also has it's own constructor method, you must at least forward a call to it and support the $attribute parameter:

public function __construct(array $attributes = array(), Mailer $mailer)
{
    $this->mailer = $mailer;

    parent::__construct($attributes);
}

EDIT

Opened an issue to understand it: https://github.com/laravel/framework/issues/3862

EDIT 2

As I've said in comment, you better create a service, as pointed by yourself, is a better application design. You should not be using your model to send e-mails. A service that receives a user model (or just name and e-mail) and send the message to that user would be a better way to go.

Answer given by Taylor Otwell about it in the issue:

Models aren't really meant to have dependencies injected into them that way. Kind of just the style of ActiveRecord style ORMs I guess. I would suggest passing the User to a Mailer class or something similar. Or if you're comfortable with it you could use App::make to grab an instance of Mail from the model instance, especially if you only need that dependency from a single method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!