Laravel DI: call control method without passing the input variable, is this possible?

class SomeController extends Controller { public function doALot(Request $request) { $this -> doOne($someOtherVariable); // Type error: Argument 1 passed to App\Http\Controllers\SomeController::doOne() must be an instance of Illuminate\Http\Request $this -> doOne($request, $someOtherVariable); // Bad practice? ... } public function doOne(Request $request, $someOtherVariable) {} ... } 

So, how to call doOne() from doALot() without passing the embedded resource, but having Request in doOne() ? It seems like bad practice goes through $request everywhere.

Solution tl; dr is impossible, but there are other ways - read a short answer from Alexei Mezenin

Long version (maybe not the best, but enough).

 $ php artisan make:provider SomeServiceProvider 

Then, in the created provider, edit register() calling something along the lines of:

 public function register() { $this -> app -> bind('App\Services\SomeService', function ($app) { return new SomeService(); }); } 

Then, go on to create a service class to which the resource attribute will be added.

 <?php namespace App\Services; use \Illuminate\Support\Facades\Request; class SomeService { private $request; /** * SomeService constructor. */ public function __construct(Request $request) { $this -> request = $request; } public function doOne($someOtherVariable) {} } 

Then move your methods from the controller for maintenance and instead add the service to the controller.

Trade-offs: (-) two useless files to perform basic functions, (+) separate the logical implementation from the controller, (~), probably more clean code.

+5
source share
1 answer

It is not recommended to invoke controller actions manually. Logic must be in the service class . You can see an example of this in my Laravel repair. If you do not want to pass the $request object each time, you can introduce the Request class in the service class or controller constructor.

Another way to use Request data is to use the request() helper:

 request('key') request()->has('key') 

Or Request facade:

 Request::has('key') 

Or you can manually enter it inside the method:

 $request = app('Illuminate\Http\Request'); 
+2
source

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


All Articles