laravel 路由 bingTo 把路由URL映射到匿名回调函数上,框架会把匿名回调函数绑定到应用对象上,这样在匿名函数中就可以使用$this关键字引用重要的应用对象。Illuminate\Support\Traits\Macroable的__call方法。
自己写一个简单的demo:
<?php
<?phpnamespace Hjj\DesignPatterns\Tests;use PHPUnit\Framework\TestCase;
class App {protected $routes = [];protected $responseStatus = '200 OK';protected $responseContentType = 'text/html';protected $responseBody = 'Laravel学院';public function addRoute($routePath, $routeCallback) {$this->routes[$routePath] = $routeCallback->bindTo($this, __CLASS__);}public function dispatch($currentPath) {foreach ($this->routes as $routePath => $callback) {if( $routePath === $currentPath) {$callback();}}
// header('HTTP/1.1 ' . $this->responseStatus);
// header('Content-Type: ' . $this->responseContentType);
// header('Content-Length: ' . mb_strlen($this->responseBody));return $this->responseBody;}}
class Closure extends TestCase
{public function testClosure () {$app = new App();$app->addRoute('user/nonfu', function(){$this->responseContentType = 'application/json;charset=utf8';$this->responseBody = '{"name":"LaravelAcademy"}';});$result = $app->dispatch('user/nonfu');$this->assertSame('{"name":"LaravelAcademy"}', $result);}
}