php – MVC中的依赖注入

我正在尝试创建简单的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

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

一些例子:

>控制器可能需要Config才能获得输出格式选项.
> Mapper可能需要数据库来执行查询.
>任何Controller / Helper都需要访问Log.
> 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.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...