简体   繁体   English

自动加载 PSR-4 特定类

[英]Autoload PSR-4 Specific Class

I have autoload setup via PSR-4 which works perfectly fine.我通过 PSR-4 进行了自动加载设置,效果很好。 However I want to be able to add a specific class on top of that, that I can access from anywhere in the application.但是我希望能够在此之上添加一个特定的类,我可以从应用程序的任何地方访问它。

This is what I have currently:这是我目前所拥有的:

    "autoload": {
       "psr-4": {
          "App\\": "app"
         }
     }

However I want to add a class called 'Redis' which is located in app/Lib/Redis.php so that from any Controller I can call Redis::method();但是我想添加一个名为“Redis”的类,它位于 app/Lib/Redis.php 中,这样我就可以从任何控制器调用 Redis::method(); without having to add 'use App\\Lib\\Redis;'无需添加“使用 App\\Lib\\Redis;” to the top of each file.到每个文件的顶部。

Is this possible?这可能吗?

This can't be done directly.这不能直接完成。

You could create a global function redis() and register than with composer:您可以创建一个全局函数 redis() 并注册而不是使用 Composer:

"autoload": {
    "psr-4": {
        "App\\": "app"
    },
    "files"" {
        "app/functions.php",
    }
}

If this redis() function returned an instance of your Redis class, then I think that you could then do:如果这个redis()函数返回了你的Redis类的一个实例,那么我认为你可以这样做:

redis()->method();

Whether you should do this or not is another matter - unit testing becomes highly problematic .你是否应该这样做是另一回事——单元测试变得很成问题 Personally, I would have a use statement and inject an instance of the Redis object into the constructors of the classes that need it.就我个人而言,我会有一个 use 语句,并将Redis对象的一个​​实例注入到需要它的类的构造函数中。

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

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