草庐IT

php - Controller 中的 Laravel 绑定(bind)接口(interface)

coder 2024-05-05 原文

是否可以将接口(interface)绑定(bind)到 Laravel Controller 中的实现?类似于以下非常粗略的示例:

if($property->param == 1){
    $mailSourceData = bind('MailInterface', 'gmailProviderRepo')
{
else if($property->param == 2){
    $mailSourceData = bind('MailInterface', 'yahooProviderRepo')
}

$mailSourceData->sendMail($emailBody);

这不适用于服务提供者中的上下文绑定(bind),因为那时我不知道我需要哪个接口(interface)实现,而且“$property”对服务提供者不可用。

最佳答案

你可以使用 Laravel 的服务容器:

https://laravel.com/docs/5.0/container

我认为单例可能是您的选择:

$this->app->singleton('FooBar', function($app)
{
    return new FooBar($app['SomethingElse']);
});

您可以使用任何您想要的键,不需要是接口(interface)或类名,即使它是值得推荐的。

然后你可以这样调用它:

$fooBar = $this->app->make('FooBar');

要自动加载它以便始终可以访问,您可以使用服务提供商:

https://laravel.com/docs/5.6/providers

可以查看原邮件服务商是如何设置的,复制一些思路:

https://github.com/laravel/framework/blob/5.6/src/Illuminate/Mail/MailServiceProvider.php

默认的邮件服务提供商是:

/**
 * Register the Illuminate mailer instance.
 *
 * @return void
 */
protected function registerIlluminateMailer()
{
    $this->app->singleton('mailer', function ($app) {
        $config = $app->make('config')->get('mail');

        // Once we have create the mailer instance, we will set a container instance
        // on the mailer. This allows us to resolve mailer classes via containers
        // for maximum testability on said classes instead of passing Closures.
        $mailer = new Mailer(
            $app['view'], $app['swift.mailer'], $app['events']
        );

        if ($app->bound('queue')) {
            $mailer->setQueue($app['queue']);
        }

        // Next we will set all of the global addresses on this mailer, which allows
        // for easy unification of all "from" addresses as well as easy debugging
        // of sent messages since they get be sent into a single email address.
        foreach (['from', 'reply_to', 'to'] as $type) {
            $this->setGlobalAddress($mailer, $config, $type);
        }

        return $mailer;
    });
}

它使用单例 $app['swift.mailer'],创建为:

/**
 * Register the Swift Mailer instance.
 *
 * @return void
 */
public function registerSwiftMailer()
{
    $this->registerSwiftTransport();

    // Once we have the transporter registered, we will register the actual Swift
    // mailer instance, passing in the transport instances, which allows us to
    // override this transporter instances during app start-up if necessary.
    $this->app->singleton('swift.mailer', function ($app) {
        return new Swift_Mailer($app['swift.transport']->driver());
    });
}

这个使用 $app['swift.transport'] 创建:

/**
 * Register the Swift Transport instance.
 *
 * @return void
 */
protected function registerSwiftTransport()
{
    $this->app->singleton('swift.transport', function ($app) {
        return new TransportManager($app);
    });
}

您可以在此处查看 TransportManager 的代码:

https://github.com/laravel/framework/blob/5.6/src/Illuminate/Mail/TransportManager.php

它使用默认驱动程序,因为没有其他驱动程序传递给方法 driver()

重用此代码可能很有趣,但它从配置中获取值,并且除非我们覆盖配置(在这种情况下根本不推荐!),否则无法传递其他值!

所以剩下的唯一选择就是脏复制粘贴。

您可以创建一个新的 TransportManager 来支持不同的驱动程序,但这会使它过于复杂,我想现在只支持 smtp 驱动程序就足够了。

您的自定义邮件服务提供商可能是这样的:

    <?php

namespace App\Providers;

use Swift_Mailer;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
use Swift_SmtpTransport as SmtpTransport;

class MultipleMailServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerMultipleMailer();
    }

    /**
     * Register the Illuminate mailer instance.
     *
     * @return void
     */
    protected function registerMultipleMailer()
    {
        foreach ($this->app->make('config')->get('mail.multiple') as $key => $config) {
            $this->app->singleton($key, function ($app) use ($config) {
                // Once we have create the mailer instance, we will set a container instance
                // on the mailer. This allows us to resolve mailer classes via containers
                // for maximum testability on said classes instead of passing Closures.
                $mailer = new Mailer(
                    $app['view'], new Swift_Mailer($this->createSmtpDriver($config)), $app['events']
                );

                // Next we will set all of the global addresses on this mailer, which allows
                // for easy unification of all "from" addresses as well as easy debugging
                // of sent messages since they get be sent into a single email address.
                foreach (['from', 'reply_to', 'to'] as $type) {
                    $this->setGlobalAddress($mailer, $config, $type);
                }

                return $mailer;
            });
        }
    }

    /**
     * Set a global address on the mailer by type.
     *
     * @param  \Illuminate\Mail\Mailer  $mailer
     * @param  array  $config
     * @param  string  $type
     * @return void
     */
    protected function setGlobalAddress($mailer, array $config, $type)
    {
        $address = Arr::get($config, $type);

        if (is_array($address) && isset($address['address'])) {
            $mailer->{'always'.Str::studly($type)}($address['address'], $address['name']);
        }
    }

    /**
     * Create an instance of the SMTP Swift Transport driver.
     *
     * @param array $config
     *
     * @return \Swift_SmtpTransport
     */
    protected function createSmtpDriver($config)
    {
        // The Swift SMTP transport instance will allow us to use any SMTP backend
        // for delivering mail such as Sendgrid, Amazon SES, or a custom server
        // a developer has available. We will just pass this configured host.
        $transport = new SmtpTransport($config['host'], $config['port']);

        if (isset($config['encryption'])) {
            $transport->setEncryption($config['encryption']);
        }

        // Once we have the transport we will check for the presence of a username
        // and password. If we have it we will set the credentials on the Swift
        // transporter instance so that we'll properly authenticate delivery.
        if (isset($config['username'])) {
            $transport->setUsername($config['username']);

            $transport->setPassword($config['password']);
        }

        // Next we will set any stream context options specified for the transport
        // and then return it. The option is not required any may not be inside
        // the configuration array at all so we'll verify that before adding.
        if (isset($config['stream'])) {
            $transport->setStreamOptions($config['stream']);
        }

        return $transport;
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array_keys($this->app->make('config')->get('mail.multiple'));
    }
}

然后您可能需要将数据添加到您的 mail.php 配置文件(或另一个配置文件)中,例如:

'multiple' => [
    'mailer.gmail' => [
        'host'       => env('MAIL_GAMIL_HOST', 'smtp.mailgun.org'),
        'port'       => env('MAIL_GAMIL_PORT', 587),
        'from'       => [
            'address' => env('MAIL_GAMIL_FROM_ADDRESS', 'hello@example.com'),
            'name'    => env('MAIL_GAMIL_FROM_NAME', 'Example'),
        ],
        'encryption' => env('MAIL_GAMIL_ENCRYPTION', 'tls'),
        'username'   => env('MAIL_GAMIL_USERNAME'),
        'password'   => env('MAIL_GAMIL_PASSWORD'),
    ],
    'mailer.yahoo' => [
        'host'       => env('MAIL_YAHOO_HOST', 'smtp.mailgun.org'),
        'port'       => env('MAIL_YAHOO_PORT', 587),
        'from'       => [
            'address' => env('MAIL_YAHOO_FROM_ADDRESS', 'hello@example.com'),
            'name'    => env('MAIL_YAHOO_FROM_NAME', 'Example'),
        ],
        'encryption' => env('MAIL_YAHOO_ENCRYPTION', 'tls'),
        'username'   => env('MAIL_YAHOO_USERNAME'),
        'password'   => env('MAIL_YAHOO_PASSWORD'),
    ],
],

不要忘记注册您的服务提供商:

https://laravel.com/docs/5.6/providers#registering-providers

'providers' => [
    // Other Service Providers

    App\Providers\MultipleMailServiceProvider::class,
],

然后,一旦服务提供商在服务容器中定义了单例,您就可以通过多种方式构建和加载创建的单例。一种方法是:

    switch ($property->param) {
        case 1:
            $mailSourceData = app('mailer.gmail');
            break;
        case 2:
            $mailSourceData = app('mailer.yahoo');
            break;
        default:
            throw new \InvalidArgumentException('Invalid property param');
    }

    $mailSourceData->sendMail($emailBody);

您甚至可以创建 Facedes 和别名...

https://laravel.com/docs/5.6/facades

当然,这里和那里可以进行一些可能的改进,但这只是概念验证。

关于php - Controller 中的 Laravel 绑定(bind)接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414326/

有关php - Controller 中的 Laravel 绑定(bind)接口(interface)的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  9. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  10. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

随机推荐