gpt4 book ai didi

php - MVC 中的依赖注入(inject)

转载 作者:可可西里 更新时间:2023-11-01 12:36:38 25 4
gpt4 key购买 nike

我正在尝试创建简单的 MVC 框架,但我被依赖项困住了。

这是我现在拥有的:

$config = new Config();
$database = new Database($config);
$uri = new Uri('article/5');
$request = new Request($uri);
$response = new Response;
$router = new Router;
$dispatcher = new Dispatcher($request, $response, $router);

$dispatcher->dispatch(); // Routing, instantiate controller, execute action, send response

问题是:任何对象如何访问任何依赖项?

一些例子:

  • Controller 可能需要配置来获取输出格式选项。
  • Mapper 可能需要数据库来执行查询。
  • 任何 Controller /助手都需要访问日志。
  • Helper 可能需要任意数量的依赖项(例如:Uri_Helper 需要 Router)。

我能想到的唯一可能就是使用Registry,但这违反了Demeter法则(问你真正需要什么)。

最佳答案

你写factories (优秀文章)。这可能非常无聊(如文章所述),因此您可以使用 DI 框架,例如:

  • Symfony DIC:查看 Juraj 的帖子。
  • PD
  • Yadif
  • Drip (PHP4):但是有一段时间没有更新了。

我还想指出,Misko 的博客非常有趣,并且有很多关于如何正确进行测试的好读物。特别是 guide to writing testable code必读。

P.S:我认为你应该编写工厂,因为 PHP 是一种脚本语言,你应该使用尽可能少的代码来使你的网站更快。这就是一些 PHP frameworks 的问题.

Rasmus Ledorf(PHP 发明者)的话:

Many frameworks may look very appealing at first glance because they seem to reduce web application development to a couple of trivial steps leading to some code generation and often automatic schema detection, but these same shortcuts are likely to be your bottlenecks as well since they achieve this simplicity by sacrifizing flexibility and performance. Nothing is going to build your application for you, no matter what it promises. You are going to have to build it yourself. Instead of starting by fixing the mistakes in some foreign framework and refactoring all the things that don't apply to your environment spend your time building a lean and reusable pattern that fits your requirements directly. In the end I think you will find that your homegrown small framework has saved you time and aggravation and you end up with a better product.

关于php - MVC 中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4746017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com