如何在 Laravel 中使用 App::call 方法注入

How to use method injection with App::call in Laravel

我正在使用 Laravel 5.2 并编写了我自己的服务提供商。我想将一个 Request 对象注入到 register 方法中。

基本问题是我想根据特殊请求参数调用不同的服务容器 - 当然,所有服务容器都实现相同的 interface/contract。

我收到的错误消息是:

ReflectionException in Container.php line 559:
Function registerService() does not exist

我的服务提供商是这样的:

<?php

namespace App\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use App\Contracts\Extractor;

class ExtractorServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Available services for channels
     *
     * @var array
     */
    protected $availableServices = ['AExtractor', 'ZExtractor'];

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->call('registerService');
    }

    /**
     * @param Request $request
     * @return void
     */
    protected function registerService(Request $request)
    {
        $tag = DB::table('channels')->where('id', $request->channel)->value('tag')->first()->tag;

        $selectedExtractor = $tag . 'Extractor';
        $extractor = 'AExtractor';

        if(in_array($selectedExtractor, $this->availableServices)) {
            $extractor = $selectedExtractor;
        }

        $this->app->bind('App\Contracts\Extractor', "App\Helpers\{$extractor}");
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [Extractor::class];
    }
}

如何使用 $this->app->call('registerService'); 调用我的 registerService 函数并注入 Request 对象?

问题是您以错误的方式调用 App:call:您必须指定要调用方法的对象和方法,如下所示:

$this->app->call( [ $this, 'registerService' ] );