微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/php/136711.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐