【问题标题】:Laravel 5.7 Service Container | DI / Passing parameters to a method in a controllerLaravel 5.7 服务容器 | DI / 将参数传递给控制器​​中的方法
【发布时间】:2019-01-03 19:25:58
【问题描述】:

我很难找到一个优雅的解决方案来将参数注入控制器方法。我想将我的工厂移动到服务容器中,因为对于没有经验的程序员来说代码更复杂。我尝试使用服务容器的 bindMethod 将参数注入控制器函数,但我还没有成功。

有人知道如何做到这一点吗?

我尝试将参数注入控制器方法的代码

Laravel 应用服务提供者

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $container = app();
        $container->bindMethod('TestController@index', function ($controller, $container) {
            return $controller->index('TestData');
        });
    }
}

控制器

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
    public function index($test)
    {
        // do something with the implementations.
    }
}

我想要达到的目标示例

当前情况(简化)。

public function index()
{
    $car = CarFactory::get();
    $food = FoodFactory::get();
}

我希望它看起来像这样:

public function index($car, $food)
{
    // do something with the implementations.
}

提前致谢!

【问题讨论】:

  • 向我们展示您当前如何在容器中尝试bind
  • @jszobody 马上添加,稍等。
  • 没有必要将东西绑定到容器。您可以键入提示您的依赖项,Laravel 将使用反射为您注入它作为依赖项。

标签: php laravel


【解决方案1】:

可以使用工厂向服务容器注入特定接口的实现。你可以用 bind 方法做到这一点。

<?php

namespace App\Providers;

use App\ExampleImplementation;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'App\IExample',
            function() {
                return (new factory())->make();
            }
        );
    }
}

我正在研究这是一种从控制器中删除工厂的实用方法。

谢谢大家!

【讨论】:

  • 如果这是正确答案,请选择它以便其他人看到。
  • 我会的!我必须等待 2 天才能接受自己的答案。
【解决方案2】:

你可以在构造函数中做:

private $carFactory;

public function __construct(CarFactory $carFactory){
  $this->carFactory = $carFactory;
}

然后随时使用$this-&gt;carFactory访问它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多