简体   繁体   English

在PHP依赖注入中,我是否需要“ require_once”定义依赖的php文件?

[英]In PHP Dependency Injection, do I need to “require_once” the php file where the dependency is defined?

Taking Fabien Potencier's example : 以Fabien Potencier 为例

class User
{
  function __construct($storage)
  {
    $this->storage = $storage;
  }

  // ...
}

Assuming the Storage class is defined in a different php file (say, storage.php), do I need to include it in this file where the injection is done via a require_once? 假设Storage类是在其他php文件中定义的(例如,storage.php),是否需要在通过require_once进行注入的文件中包含该类?

Thanks, 谢谢,

JDelage JDelage

You should be putting all your require s and include s at the head of the file - that certainly a style thing, but for one thing it allows you to see by glancing at the source, what other files are need by your PHP file. 您应该将所有requireinclude s放在文件的开头,这当然是一种样式,但是对于一件事,您可以通过浏览源代码来了解PHP文件还需要其他哪些文件。

There are two cases: 有两种情况:

  1. You will only ever use user.php and storage.php from other files ( app.php say) 您只会使用其他文件中的user.phpstorage.phpapp.php说)
  2. There are cases where you will use user.php and don't want to worry about remembering to require storage.php . 在某些情况下,您将使用user.php而不必担心记住需要storage.php

For #1 - you don't need to worry about requires, however there's no significant disadvantage to using require_once at the head of your PHP even if most of the time it'll have already been required. 对于#1-您不必担心需求,但是即使在大多数时间已经需要,在PHP开头使用require_once也没有明显的缺点。

For #2 - you need to use require_once at the header since you cannot use user.php without storage.php and the final page only knows it needs user.php . 对于#2-您需要在标头中使用require_once ,因为如果没有storage.php则无法使用user.php ,并且最后一页仅知道它需要user.php

short answer: Use require_once to include all dependencies for the code (to allow it to easily be used by other code) 简短答案:使用require_once包含代码的所有依赖项(以使其易于被其他代码使用)

note: You should only include direct-dependencies for the code. 注意:您只应包括代码的直接依赖项。 That is: if you have group.php that uses user.php , it should require_once 'user.php' , but need not worry about storage.php since it isn't directly used, and user.php implicitly includes it (that being said - no significant performance disadvantage of being thorough if you wish) 那就是:如果您有使用user.php group.php ,它应该是require_once 'user.php' ,但是不必担心storage.php因为它不是直接使用的,而user.php隐式地包含了它(即表示-如果您愿意的话,对性能没有明显的不利影响)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM