Laravel - 通过app->绑定模型的构造函数传递参数

时间:2014-02-13 06:20:12

标签: laravel entity service-provider

嗯,代码描述了一切。我有一个实体服务提供程序,它传递一个播放列表模型的实例,它应该得到一个数组作为它的第一个构造函数参数。如何通过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

3 个答案:

答案 0 :(得分:6)

Alex Russell的评论也适合我。

  

类似案例中的答案'据我所知,帖子是正确的。对我来说App::make('Whatever', [1, 2, 3]);后跟[1, 2, 3] var_dumps $(document).ready(function(e) { var dataRows = []; //Create an array of all rows with its value (this assumes that the amount is always a number. You should add error checking!! Also assumes that all rows are data rows, and that there are no header rows. Adjust selector appropriately. $('tr').each(function(i,j) { dataRows.push({'amount': parseFloat($(this).find('.amount').text().replace(/[^\d\.\-]/g, '')), 'row': $(this)}); }) //Sort the data smallest to largest dataRows.sort(function(a, b) { return a.amount - b.amount; }); //Remove existing table rows. This assumes that everything should be deleted, adjust selector if needed :). $('table').empty(); //Add rows back to table in the correct order. dataRows.forEach(function(ele) { $('table').append(ele.row); }) }) 数组。

答案 1 :(得分:4)

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

顺便说一下,我试图对前一个答案做出评论,但它没有让我这么做。也许是因为经验值不够?

答案 2 :(得分:0)

感谢@ 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; });