关注点分离
我们当前框架的一个缺点是,每次创建一个新网站时,都需要复制粘贴 front.php
中的代码。 60 行代码不多,但如果我们能将这些代码封装到一个合适的类中就更好了。 这将为我们带来更好的 *可重用性* 和更轻松的测试,仅举几例好处。
如果您仔细查看代码,front.php
有一个输入,即 Request(请求),和一个输出,即 Response(响应)。 我们的框架类将遵循这个简单的原则:逻辑是关于创建与 Request 关联的 Response。
让我们为我们的框架创建自己的命名空间:Simplex
。 将请求处理逻辑移到其自身的 Simplex\Framework
类中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
// example.com/src/Simplex/Framework.php
namespace Simplex;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
class Framework
{
public function __construct(
private UrlMatcher $matcher,
private ControllerResolver $controllerResolver,
private ArgumentResolver $argumentResolver,
) {
}
public function handle(Request $request): Response
{
$this->matcher->getContext()->fromRequest($request);
try {
$request->attributes->add($this->matcher->match($request->getPathInfo()));
$controller = $this->controllerResolver->getController($request);
$arguments = $this->argumentResolver->getArguments($request, $controller);
return call_user_func_array($controller, $arguments);
} catch (ResourceNotFoundException $exception) {
return new Response('Not Found', 404);
} catch (\Exception $exception) {
return new Response('An error occurred', 500);
}
}
}
并相应地更新 example.com/web/front.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// example.com/web/front.php
// ...
$request = Request::createFromGlobals();
$routes = include __DIR__.'/../src/app.php';
$context = new Routing\RequestContext();
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);
$controllerResolver = new ControllerResolver();
$argumentResolver = new ArgumentResolver();
$framework = new Simplex\Framework($matcher, $controllerResolver, $argumentResolver);
$response = $framework->handle($request);
$response->send();
为了完成重构,让我们将除了路由定义之外的所有内容从 example.com/src/app.php
移动到另一个命名空间:Calendar
。
为了让在 Simplex
和 Calendar
命名空间下定义的类能够被自动加载,请更新 composer.json
文件
1 2 3 4 5 6
{
"...": "...",
"autoload": {
"psr-4": { "": "src/" }
}
}
注意
要更新 Composer 自动加载器,请运行 composer dump-autoload
。
将控制器移动到 Calendar\Controller\LeapYearController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// example.com/src/Calendar/Controller/LeapYearController.php
namespace Calendar\Controller;
use Calendar\Model\LeapYear;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class LeapYearController
{
public function index(Request $request, int $year): Response
{
$leapYear = new LeapYear();
if ($leapYear->isLeapYear($year)) {
return new Response('Yep, this is a leap year!');
}
return new Response('Nope, this is not a leap year.');
}
}
并将 is_leap_year()
函数也移动到它自己的类中
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// example.com/src/Calendar/Model/LeapYear.php
namespace Calendar\Model;
class LeapYear
{
public function isLeapYear(?int $year = null): bool
{
if (null === $year) {
$year = date('Y');
}
return 0 == $year % 400 || (0 == $year % 4 && 0 != $year % 100);
}
}
不要忘记相应地更新 example.com/src/app.php
文件
1 2 3 4
$routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [
'year' => null,
'_controller' => 'Calendar\Controller\LeapYearController::index',
]));
总结一下,这是新的文件布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
example.com
├── composer.json
├── composer.lock
├── src
│ ├── app.php
│ └── Simplex
│ └── Framework.php
│ └── Calendar
│ └── Controller
│ │ └── LeapYearController.php
│ └── Model
│ └── LeapYear.php
├── vendor
│ └── autoload.php
└── web
└── front.php
就是这样! 我们的应用程序现在有四个不同的层,每个层都有明确的目标
web/front.php
:前端控制器;唯一暴露的 PHP 代码,它与客户端进行接口交互(获取 Request 并发送 Response),并提供初始化框架和应用程序的样板代码;src/Simplex
:可重用的框架代码,它抽象了对传入 Request 的处理(顺便说一句,它使您的控制器/模板更易于测试 —— 稍后会详细介绍);src/Calendar
:我们应用程序特定的代码(控制器和模型);src/app.php
:应用程序配置/框架自定义。
这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可协议获得许可。