How can I override the Laravel Facade methods?

I want to override the Laravels' Mail send class facade method (just intercept it by force checking some checks, and then if it passes with parent :: send () running)

What is the best way to do this?

+4
source share
1 answer

The facade does not work like that. This is essentially a kind of wrapper class that calls the base class that it represents.

The facade has Mailvirtually no method send. When you do Mail::send(), under the hood, the “facade accessory” is used to refer to an instance of the class Illuminate\Mail\Mailerbound in the IoC container. A method is called on this object send.

, , , , . , :

  • Mailer, Illuminate\Mail\Mailer, send, parent::send().
  • ( Illuminate\Mail\MailServiceProvider), , register. Mailer Laravel. ( Laravel register).
  • , config/app.php , providers Illuminate\Mail\MailServiceProvider::class, .

Laravel Mail.


/, . Mail , , Mailer.

Mailer Laravel


/MyMailer/Mailer.php

<?php

namespace App\MyMailer;

class Mailer extends \Illuminate\Mail\Mailer
{
    public function send($view, array $data = [], $callback = null)
    {
        // Do your checks

        return parent::send($view, $data, $callback);
    }
}

app/MyMailer/MailServiceProvider.php ( , Laravel MailServiceProvider)

<?php

namespace App\MyMailer;

class MailServiceProvider extends \Illuminate\Mail\MailServiceProvider
{
    public function register()
    {
        $this->registerSwiftMailer();

        $this->app->singleton('mailer', function ($app) {
            // This is YOUR mailer - notice there are no `use`s at the top which
            // Looks for a Mailer class in this namespace
            $mailer = new Mailer(
                $app['view'], $app['swift.mailer'], $app['events']
            );

            $this->setMailerDependencies($mailer, $app);


            $from = $app['config']['mail.from'];

            if (is_array($from) && isset($from['address'])) {
                $mailer->alwaysFrom($from['address'], $from['name']);
            }

            $to = $app['config']['mail.to'];

            if (is_array($to) && isset($to['address'])) {
                $mailer->alwaysTo($to['address'], $to['name']);
            }

            return $mailer;
        });
    }
}

config/app.php ( )

//...
// Illuminate\Mail\MailServiceProvider::class,
App\MyMailer\MailServiceProvider::class,
//...
+6

Source: https://habr.com/ru/post/1655524/


All Articles