php – MVC中的依赖注入

前端之家收集整理的这篇文章主要介绍了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.

@H_301_34@
原文链接:https://www.f2er.com/php/136711.html

猜你在找的PHP相关文章