且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

作曲家自动加载文件不起作用

更新时间:2023-10-17 17:28:04

自动加载在这里不起作用.PHP 只能自动加载类.您期望 app/routes.php 将被自动加载是不可能的,因为该文件不包含类声明,并且您无法使用以前未知的类来触发它的执行.

Autoloading won't work here. PHP can only autoload classes. Your expectation that app/routes.php will be autoloaded is not possible, because that file does not contain a class declaration, and you are not able to trigger it's execution by using a previously unknown class.

确实,当您包含 vendor/autoload.php 时,Composer 会执行该文件一次 - 但是,这确实是您的软件的不良行为.不要使用文件"自动加载来包含配置文件.请注意这在库中使用时可能会对性能产生影响.您应该完全避免使用它,它旨在用于无法正常工作的遗留代码.

It is true that Composer will execute that file once when you include vendor/autoload.php - however, this is really bad behavior of your software. Don't use the "files" autoloading to include configuration files. Mind the performance impact this may have when being used in libraries. You should avoid using it altogether, it is meant to be used for legacy code that cannot otherwise be made working.

另一方面,您的架构已损坏.您不应该仅仅通过访问一个应该在其他地方初始化的变量来编写一个神奇地"知道配置的类.一个好的模式是将配置作为参数传递给构造函数:

On the other hand, your architecture is broken. You shouldn't write a class that "magically" knows about the configuration just by accessing a variable that is supposed to be initialized somewhere else. A good pattern would be to pass the configuration as a parameter to the constructor:

public function __construct ($routes)
{
    $this->routes = $routes;
}

创建此类的代码部分应该从某处获取配置并将其作为参数传递.这个概念称为控制反转或依赖注入:类不会调用它们需要使用的其他类,它们会请求它们并将它们作为参数获取.

The part of the code that creates this class is supposed to grab the configuration from somewhere and pass it as a parameter. This concept is called inversion of control or dependency injection: Classes do not invoke the other classes they need to work with, they ask for them and get them as a parameter.