简体   繁体   English

laravel 中的依赖注入问题

[英]Issue with dependency injection in laravel

I just learnt of laravel's service container and dependency injection, in order to try this out I created a MailgunServiceProvider to instantiate mailgun client, I laso have a trait called SendMail which acts as a wrapper for Mailgun:我刚刚了解了 laravel 的服务容器和依赖注入,为了尝试这一点,我创建了一个 MailgunServiceProvider 来实例化 mailgun 客户端,我也有一个名为 SendMail 的特性,它充当 Mailgun 的包装器:

However the $mailgun variable returns null, I'm getting the following message:但是 $mailgun 变量返回 null,我收到以下消息:

message Call to a member function messages() on null
exception   Symfony\Component\Debug\Exception\FatalThrowableError
file    C:\xampp\htdocs\dogmedia.com\app\Traits\SendMail.php
line    24

MailgunServiceProvider MailgunServiceProvider

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Mailgun\HttpClientConfigurator;
use Mailgun\Mailgun;



class MailgunServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Mailgun::class, function()
        {
            return Mailgun::create(config('mail.mailgun.secret'), 'https://api.eu.mailgun.net');
        });
    }
}

And my trait:还有我的特点:

<?php
namespace App\Traits;

use Mailgun\Mailgun;


trait SendMail
{

    protected $mailgun;

    public function __construct(Mailgun $mailgun)
    {
        $this->mailgun = $mailgun;
    }


    public function sendMail($view, $mailData, $subject, $to)
    {
        //dd($this->mailgun); this returns null

        $html = view($view, compact('mailData'))->render();

        $result = $this->mailgun->messages()->send(config('mail.mailgun.domain'), [
            'from' => config('mail.from.name').' <'.config('mail.from.address').'>',
            'to' => $to,
            'subject' => $subject,
            'html' => $html,
        ]);

        return $result;
    }


}

This is the class inviking my trait.这是 class 激发我的特质。

<?php
namespace App\Http\Controllers;


use Mailgun\Mailgun;
use Illuminate\Http\Request;
use App\Http\Validators\ContactValidator;
use App\Models\General;
use App\Models\Post;
use App\Traits\SendMail;


class ContactController extends Controller
{
    use SendMail;


    public function __construct(){}


    public function sendContactMail1(Request $request)
    {
        //$validatedData = $request->validate(ContactValidator::$sendContactMail1);

        $mailData = 
        [
            'phone'=> $request->input('phone')
        ];

        $mail = $this->sendMail('emails.contacts.contact-mail-1', $mailData, 'Nuevo contacto en '.config('app.name'), 'gabogabans@gmail.com');

        return response()->json([
            'mail' => $mail,
        ]);
    }


}

The methods defined in the class definition will take priority over the trait methods. class 定义中定义的方法将优先于特征方法。 So if your class has a constructor defined then the trait's constructor method will not be applied.因此,如果您的 class 定义了构造函数,则不会应用特征的构造函数方法。

"An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods." “从基础 class 继承的成员被由 Trait 插入的成员覆盖。优先顺序是来自当前 class 的成员覆盖 Trait 方法,进而覆盖继承的方法。” PHP Manual - Traits - Precedence PHP 手册 - 特征 - 优先级

class RandomClass
{
    use SendMail;

    public function __construct()
    {
    }
}

The constructor defined in the class will be used instead of the method with the same name from the trait.将使用 class 中定义的构造函数,而不是特征中具有相同名称的方法。

You could avoid dealing with the constructor completely by having the sendMail method get an instance of the Mailgun class that you need from the container instead, if you prefer:如果您愿意,您可以通过让sendMail方法从容器中获取您需要的 Mailgun class 实例来完全避免处理构造函数:

$mailgun = app(\Mailgun\Mailgun::class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM