doutizong8099 2016-03-23 11:53
浏览 116
已采纳

如何通过服务容器将参数传递给构造函数?

I have a class that is responseible for calling a 3rd party payment solution.

As a part of this, there are various merchant id/shared secret parameters. Theses will depend on who's logged into the application.

The class I'm working with takes this info in the constructor when the class is built. Is there a way to pass this in the service provider, perhaps like this:

 $this->app->bind( 'App\BokaKanot\Interfaces\BillingInterface',function ($merchantId)
 {
    return new KlarnaBilling($merchantId);
 } );

If so, is it still possible to do this through a constructor or do I need to manaully use App:make. If I do have to use App::make, how can I not hide this inside my calling class?

Or should I refactor the class I'm using to not need this in the constructor, and perhaps have an init method?

  • 写回答

2条回答 默认 最新

  • dongyi1441 2016-03-23 12:23
    关注

    You can pass parameters to App::make and pass the parameters to the constructor like this:

    $this->app->bind( 'App\BokaKanot\Interfaces\BillingInterface',
                       function( $app, array $parameters)
    {
        //call the constructor passing the first element of $parameters
        return new KlarnaBilling( $parameters[0] );
    } );
    
    //pass the parameter to App::Make
    App::make( 'App\BokaKanot\Interfaces\BillingInterface',  [ $merchantId ]  );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作