dtv995719 2019-06-14 16:23
浏览 234

Laravel使用Request params更改绑定

I am using Laravel Framework 5.8.21. I am trying to bind an interface to a class based on Request params inside AppServiceProvider's register method like this.

public function register()
{
  $this->app->bind('App\Contracts\SomeInterface', 'App\Logic\ClassName');
  if(Request::has('notification_type') && Request::get('notification_type') == 'email') {
    $this->app->bind('App\Contracts\SomeInterface', 'App\Logic\SomeotherClassName');
  }
}

and later injecting the interface to Controllers __construct() method.

with tests, it always bound to ClassName. I tried to get accessed URL inside AppServiceProvider and while running unit tests, it always returning / with $this->app->request->getRequestUri(); and method as GET even though from the test I am posting to URL like this.

$this->post('/notification', [
            'notification_type' => 'email',
  ])->assertJson(   
     'message-push-status' => true,
  ]);

While testing it with Postman, when I try to post http://localhost:8000/notification, it says, 419 | Page Expired.

  • 写回答

1条回答 默认 最新

  • duanjianhe1388 2019-06-15 04:15
    关注

    You will not be able to reliably use the current request information from within a service provider.

    First, it is a general best practice to not depend on application logic within the register() method directly. You may cause a race condition where you have a dependency that hasn't been registered yet, or cause unnecessary overhead (e.g. establish a database connection even if you don't need any querying).

    Second, Laravel's request lifecycle won't funnel the current request into the application until after all of the service provider registration and bootstrapping has been completed.

    Without knowing exactly what business logic you're trying to accomplish, you have at least a couple options:

    1. Use contextual binding to serve different implementations of the same interface depending on the requesting object (e.g. controller).

    2. Use a factory or a similar facilitator-style object that you can inject in the controller, and can provide the proper dependency based on your preferred logic.

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧