codedge codedge - 6 months ago 73
PHP Question

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

I am using Laravel 5.2 and wrote my own Service Provider. I want to inject a Request object into the register method.

The base problem is that I want to call different service container depending on a special request param - all the service container implementing the same interface/contract of course.

The error message I am getting is:

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


My service provider looks like that:

<?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];
}
}


How can I use
$this->app->call('registerService');
to call my
registerService
function and inject the Request object?

Answer

The problem is you're calling App:call in a wrong way: you have to specify the object on which you want to call the method and the method, like this :

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