加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – MVC中的依赖注入

发布时间:2020-12-13 13:12:30 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试创建简单的MVC骨架,并且我坚持使用依赖项. 这就是我现在拥有的: $config = new Config();$database = new Database($config);$uri = new Uri('article/5');$request = new Request($uri);$response = new Response;$router = new Router;$dispatc
我正在尝试创建简单的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读