【问题标题】:Laravel - pass parameters through app->bind to model's constructorLaravel - 通过 app->bind 传递参数到模型的构造函数
【发布时间】:2014-03-11 21:15:12
【问题描述】:

好吧,代码描述了一切。我有一个实体服务提供者,它传递一个播放列表模型的实例,它应该获取一个数组作为它的第一个构造函数参数。如何通过 app->bind 传递该参数?知道在控制器中引用 EntityServiceProvider 时会自动注入。

        // Current Code
        /**
         * Playlist Entity
         *
         * @return Playlist\PlaylistEntity
         */
        $this->app->bind('Playlist\PlaylistEntity', function($app)
        {
            return new PlaylistEntity($app->make('Playlist\PlaylistRepositoryInterface'));
        });



        // Should be something like this:
        /**
         * Playlist Entity
         *
         * @return Playlist\PlaylistEntity
         */
        $this->app->bind('Playlist\PlaylistEntity', function($app)
        {
            return new PlaylistEntity($app->make('Playlist\PlaylistRepositoryInterface', $parameters));
        });

类似情况:Laravel 4: Passing data from make to the service provider

【问题讨论】:

  • 据我所知,“类似案例”帖子中的答案是正确的。 $this->app->bind('Whatever', function ($app, $params) { var_dump($params); }); 后跟 App::make('Whatever', [1, 2, 3]); var_dump 为我转储 [1, 2, 3] 数组。
  • 如何使用 Facades not make 做到这一点?有没有可能

标签: laravel entity service-provider


【解决方案1】:

Alex Russell 的评论也对我有用。

据我所知,“类似案例”帖子中的答案是正确的。 $this->app->bind('Whatever', function ($app, $params) { var_dump($params); }); 后跟 App::make('Whatever', [1, 2, 3]); var_dump 为我转储 [1, 2, 3] 数组。

【讨论】:

  • 已确认。也适用于我,即使在最新版本 (5.3) 中也是如此
【解决方案2】:

在 Laravel 5.4 中,使用 App::make() 从容器解析时传递配置参数的功能被删除,随后 re-implemented as App::makeWith() 被删除。

顺便说一句,我试图对上一个答案发表评论,但它没有让我这样做。可能是因为经验值不够?

【讨论】:

  • 小心makeWithmake 不一样,它不允许像app()->instance(MyClass::class, $myObject); 这样的测试用例在应用程序容器中放置另一个对象,现在模拟被打破了。即使在 laravel 5.6 中
【解决方案3】:

感谢@yevgeniy-afanasyev 在嘲笑时指出问题。如果您需要模拟这些实例,您可以在这里参考 Taylor Otwell 的早期建议:https://github.com/laravel/ideas/issues/391#issuecomment-285197048

我只是需要它,而且效果很好。当你 ::make 时,只需返回一个闭包并调用它。

// Service Provider
$this->app->bind(MyClass::class, function ($app) {
   return function($param) : MyClass
   {
       return new MyClass($param);
   }
}

// ::make
$myInstance = App::make(MyClass::class)($myParameter);

// mock
$myMock = Mockery::mock(new MyClass($myParameter));
$this->instance(MyClass::class, function($param) use ($myMock) { return $myMock; });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多