Strategy to override a class in a library installed with Composer

前端 未结 4 1890
抹茶落季
抹茶落季 2020-12-13 00:50

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? S

4条回答
  •  旧巷少年郎
    2020-12-13 01:18

    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"
             }
         }
    }
    

    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.

    EDIT: 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.

提交回复
热议问题