覆盖使用 Composer 安装的库中的类的策略

2022-01-21 00:00:00 php composer-php codeigniter

我正在使用 Codeigniter 和 Composer.要求之一是 PHPExcel.现在我需要更改其中一个类中的函数.最好的策略应该是什么?我应该更改供应商文件夹中的代码吗?如果是这样,如何维护所有实例的更改?如果不是,我如何覆盖该特定类.虽然我提到了 PHPExcel,但我想要一个通用的解决方案.

I am using Codeigniter and Composer. One of the requirements is PHPExcel. Now I need to change a function in one of the classes. What should be the best strategy to do it? Should I change the code in the vendor folder? If so, how to maintain the change across all the instances? If not how do I override that particular class. Though I mention PHPExcel I would like a generic solution.

我不确定这是否是这个问题的正确论坛.如果不是,我将删除它.如果需要更多详细信息,请告诉我.

I am not sure if this is the right forum for this question. If not i will remove this. Please let me know if any more details are needed.

谢谢.

推荐答案

在composer.json的["autoload"]["psr-4"]下,添加一个以namespace为key、path为value的条目:

In composer.json, under ["autoload"]["psr-4"], add an entry with namespace as the key and path as the value:

{
     "autoload": {

         "psr-4": {

             "BuggyVendor\Namespace\": "myfixes/BuggyVendor/Namespace"
         }
     }
}

在该路径下复制您要覆盖的文件(保留子命名空间目录结构)并在那里编辑它们.将优先选择它们,而不是库包的原始类路径".似乎以这种方式添加到 composer.json 的命名空间->路径映射在被必需包添加的映射之前被考虑.注意:我刚刚尝试过,它确实有效,但我不知道这是否是预期功能或可能的问题.

Copy files you want to override under that path (keeping sub-namespace directory structure) and edit them there. They will be picked in preference to the library package's original "classpath". It would seem that namespace->path mappings added to composer.json in this manner are considered before those added by required packages. Note: I just tried it and it worked, though I don't know if it is an intended feature or what possible gotchas are.

发现了一个问题.有时,当您随后使用 composer require vendor/package 需要另一个包时,您将丢失"覆盖.如果发生这种情况,您必须手动发出 composer dump-autoload.这将恢复正确的自动加载顺序,以尊重您的覆盖.

found a gotcha. Sometimes when you subsequently require another package with composer require vendor/package, you will "lose" the override. If this happens, you must issue composer dump-autoload manually. This will restore the correct autoload order honoring your override.

相关文章