当前位置: 首页 > 文档资料 > Laravel 源码详解 >

Laravel Route 路由 - Laravel HTTP——SubstituteBindings 参数绑定中间件的使用与源码解析

优质
小牛编辑
128浏览
2023-12-01

当路由与请求进行正则匹配后,各个路由的参数就获得了它们各自的数值。然而,有些路由参数变量,我们还想要把它转化为特定的对象,这时候就需要中间件的帮助。 SubstituteBindings 中间件就是一个将路由参数转化为特定对象的组件,它默认可以将特定名称的路由参数转化数据库模型对象,可以转化已绑定的路由参数为把绑定的对象。

SubstituteBindings 中间件的使用

数据库模型隐性转化

首先我们定义了一个带有路由参数的路由:

  1. Route::put('user/{userid}', 'UserController@update');

然后我们在路由的控制器方法中或者路由闭包函数中定义一个数据库模型类型的参数,这个参数名与路由参数相同:

  1. class UserController extends Controller
  2. {
  3. public function update(UserModel $userid)
  4. {
  5. $userid->name = 'taylor';
  6. $userid->update();
  7. }
  8. }

这时,路由的参数会被中间件隐性地转化为 UserModel,且模型变量 $userid 的主键值为参数变量 {userid} 正则匹配后的数值。

综合测试样例:

  1. public function testImplicitBindingsWithOptionalParameter()
  2. {
  3. unset($_SERVER['__test.controller_callAction_parameters']);
  4. $router->get(($str = str_random()).'/{user}/{defaultNull?}/{team?}', [
  5. 'middleware' => SubstituteBindings::class,
  6. 'uses' => 'IlluminateTestsRoutingRouteTestAnotherControllerWithParameterStub@withModels',
  7. ]);
  8. $router->dispatch(Request::create($str.'/1', 'GET'));
  9. $values = array_values($_SERVER['__test.controller_callAction_parameters']);
  10. $this->assertEquals(1, $values[0]->value);
  11. }
  12. class RouteTestAnotherControllerWithParameterStub extends Controller
  13. {
  14. public function callAction($method, $parameters)
  15. {
  16. $_SERVER['__test.controller_callAction_parameters'] = $parameters;
  17. }
  18. public function withModels(RoutingTestUserModel $user)
  19. {
  20. }
  21. }
  22. class RoutingTestUserModel extends Model
  23. {
  24. public function getRouteKeyName()
  25. {
  26. return 'id';
  27. }
  28. public function where($key, $value)
  29. {
  30. $this->value = $value;
  31. return $this;
  32. }
  33. public function first()
  34. {
  35. return $this;
  36. }
  37. public function firstOrFail()
  38. {
  39. return $this;
  40. }
  41. }

路由显示绑定

除了隐示地转化路由参数外,我们还可以给路由参数显示提供绑定。显示绑定有 bindmodel 两种方法。

  • 通过 bind 为参数绑定闭包函数:
  1. public function testRouteBinding()
  2. {
  3. $router = $this->getRouter();
  4. $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) {
  5. return $name;
  6. }]);
  7. $router->bind('bar', function ($value) {
  8. return strtoupper($value);
  9. });
  10. $this->assertEquals('TAYLOR', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
  11. }
  • 通过 bind 为参数绑定类方法,可以指定 classname@method,也可以直接使用类名,默认会调用类的 bind 函数:
  1. public function testRouteClassBinding()
  2. {
  3. $router = $this->getRouter();
  4. $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) {
  5. return $name;
  6. }]);
  7. $router->bind('bar', 'IlluminateTestsRoutingRouteBindingStub');
  8. $this->assertEquals('TAYLOR', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
  9. }
  10. public function testRouteClassMethodBinding()
  11. {
  12. $router = $this->getRouter();
  13. $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) {
  14. return $name;
  15. }]);
  16. $router->bind('bar', 'IlluminateTestsRoutingRouteBindingStub@find');
  17. $this->assertEquals('dragon', $router->dispatch(Request::create('foo/Dragon', 'GET'))->getContent());
  18. }
  19. class RouteBindingStub
  20. {
  21. public function bind($value, $route)
  22. {
  23. return strtoupper($value);
  24. }
  25. public function find($value, $route)
  26. {
  27. return strtolower($value);
  28. }
  29. }
  • 通过 model 为参数绑定数据库模型,路由的参数就不需要和控制器方法中的变量名相同,laravel 会利用路由参数的值去调用 where 方法查找对应记录:
  1. if ($model = $instance->where($instance->getRouteKeyName(), $value)->first()) {
  2. return $model;
  3. }

测试样例如下:

  1. public function testModelBinding()
  2. {
  3. $router = $this->getRouter();
  4. $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) {
  5. return $name;
  6. }]);
  7. $router->model('bar', 'IlluminateTestsRoutingRouteModelBindingStub');
  8. $this->assertEquals('TAYLOR', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
  9. }
  10. class RouteModelBindingStub
  11. {
  12. public function getRouteKeyName()
  13. {
  14. return 'id';
  15. }
  16. public function where($key, $value)
  17. {
  18. $this->value = $value;
  19. return $this;
  20. }
  21. public function first()
  22. {
  23. return strtoupper($this->value);
  24. }
  25. }
  • 若绑定的 model 并没有找到对应路由参数的记录,可以在 model 中定义一个闭包函数,路由参数会调用闭包函数:
  1. public function testModelBindingWithCustomNullReturn()
  2. {
  3. $router = $this->getRouter();
  4. $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) {
  5. return $name;
  6. }]);
  7. $router->model('bar', 'IlluminateTestsRoutingRouteModelBindingNullStub', function () {
  8. return 'missing';
  9. });
  10. $this->assertEquals('missing', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
  11. }
  12. public function testModelBindingWithBindingClosure()
  13. {
  14. $router = $this->getRouter();
  15. $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) {
  16. return $name;
  17. }]);
  18. $router->model('bar', 'IlluminateTestsRoutingRouteModelBindingNullStub', function ($value) {
  19. return (new RouteModelBindingClosureStub())->findAlternate($value);
  20. });
  21. $this->assertEquals('tayloralt', $router->dispatch(Request::create('foo/TAYLOR', 'GET'))->getContent());
  22. }
  23. class RouteModelBindingNullStub
  24. {
  25. public function getRouteKeyName()
  26. {
  27. return 'id';
  28. }
  29. public function where($key, $value)
  30. {
  31. return $this;
  32. }
  33. public function first()
  34. {
  35. }
  36. }
  37. class RouteModelBindingClosureStub
  38. {
  39. public function findAlternate($value)
  40. {
  41. return strtolower($value).'alt';
  42. }
  43. }

SubstituteBindings 中间件的源码解析

  1. class SubstituteBindings
  2. {
  3. public function handle($request, Closure $next)
  4. {
  5. $this->router->substituteBindings($route = $request->route());
  6. $this->router->substituteImplicitBindings($route);
  7. return $next($request);
  8. }
  9. }

从代码来看,substituteBindings 用于显示的参数转化,substituteImplicitBindings 用于隐性的参数转化。

隐性参数转化源码解析

进行隐性参数转化,其步骤为:

  • 扫描控制器方法或者闭包函数所有的参数,提取出数据库模型类型对象
  • 根据模型类型对象的 name,找出与模型对象命名相同的路由参数
  • 根据模型类型对象的 classname,构建数据库模型类型对象,根据路由参数的数值在数据库中执行 sql 语句查询
  1. public function substituteImplicitBindings($route)
  2. {
  3. ImplicitRouteBinding::resolveForRoute($this->container, $route);
  4. }
  5. class ImplicitRouteBinding
  6. {
  7. public static function resolveForRoute($container, $route)
  8. {
  9. $parameters = $route->parameters();
  10. foreach ($route->signatureParameters(Model::class) as $parameter) {
  11. $class = $parameter->getClass();
  12. if (array_key_exists($parameter->name, $parameters) &&
  13. ! $route->parameter($parameter->name) instanceof Model) {
  14. $method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail';
  15. $model = $container->make($class->name);
  16. $route->setParameter(
  17. $parameter->name, $model->where(
  18. $model->getRouteKeyName(), $parameters[$parameter->name]
  19. )->{$method}()
  20. );
  21. }
  22. }
  23. }
  24. }

值得注意的是,显示参数转化的优先级要高于隐性转化,如果当前参数已经被 model 函数显示转化,那么该参数并不会进行隐性转化,也就是上面语句 ! $route->parameter($parameter->name) instanceof Model 的作用。

其中扫描控制器方法参数的功能主要利用反射机制:

  1. public function signatureParameters($subClass = null)
  2. {
  3. return RouteSignatureParameters::fromAction($this->action, $subClass);
  4. }
  5. class RouteSignatureParameters
  6. {
  7. public static function fromAction(array $action, $subClass = null)
  8. {
  9. $parameters = is_string($action['uses'])
  10. ? static::fromClassMethodString($action['uses'])
  11. : (new ReflectionFunction($action['uses']))->getParameters();
  12. return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) {
  13. return $p->getClass() && $p->getClass()->isSubclassOf($subClass);
  14. });
  15. }
  16. protected static function fromClassMethodString($uses)
  17. {
  18. list($class, $method) = Str::parseCallback($uses);
  19. return (new ReflectionMethod($class, $method))->getParameters();
  20. }
  21. }

bind 显示参数绑定

路由的 bind 功能由专门的 binders 数组负责,这个数组中保存着所有的需要显示转化的路由参数与他们的转化闭包函数:

  1. public function bind($key, $binder)
  2. {
  3. $this->binders[str_replace('-', '_', $key)] = RouteBinding::forCallback(
  4. $this->container, $binder
  5. );
  6. }
  7. class RouteBinding
  8. {
  9. public static function forCallback($container, $binder)
  10. {
  11. if (is_string($binder)) {
  12. return static::createClassBinding($container, $binder);
  13. }
  14. return $binder;
  15. }
  16. protected static function createClassBinding($container, $binding)
  17. {
  18. return function ($value, $route) use ($container, $binding) {
  19. list($class, $method) = Str::parseCallback($binding, 'bind');
  20. $callable = [$container->make($class), $method];
  21. return call_user_func($callable, $value, $route);
  22. };
  23. }
  24. }

可以看出,bind 函数可以绑定闭包、classname@methodclassname,如果仅仅绑定了一个类名,那么程序默认调用类中 bind 方法。

model 显示参数绑定

model 调用 bind 函数,赋给 bind 函数一个提前包装好的闭包函数:

  1. public function model($key, $class, Closure $callback = null)
  2. {
  3. $this->bind($key, RouteBinding::forModel($this->container, $class, $callback));
  4. }
  5. class RouteBinding
  6. {
  7. public static function forModel($container, $class, $callback = null)
  8. {
  9. return function ($value) use ($container, $class, $callback) {
  10. if (is_null($value)) {
  11. return;
  12. }
  13. $instance = $container->make($class);
  14. if ($model = $instance->where($instance->getRouteKeyName(), $value)->first()) {
  15. return $model;
  16. }
  17. if ($callback instanceof Closure) {
  18. return call_user_func($callback, $value);
  19. }
  20. throw (new ModelNotFoundException)->setModel($class);
  21. };
  22. }
  23. }

可以看出,这个闭包函数与隐性转化很相似,都是首先创建数据库模型对象,再利用路由参数值来查询数据库,返回对象。 model 还可以提供默认的闭包函数,以供查询不到数据库时调用。

显示路由参数转化

当运行中间件 SubstituteBindings 时,就会将先前绑定的各个闭包函数执行,并对路由参数进行转化:

  1. public function substituteBindings($route)
  2. {
  3. foreach ($route->parameters() as $key => $value) {
  4. if (isset($this->binders[$key])) {
  5. $route->setParameter($key, $this->performBinding($key, $value, $route));
  6. }
  7. }
  8. return $route;
  9. }
  10. protected function performBinding($key, $value, $route)
  11. {
  12. return call_user_func($this->binders[$key], $value, $route);
  13. }
  14. public function setParameter($name, $value)
  15. {
  16. $this->parameters();
  17. $this->parameters[$name] = $value;
  18. }