Strategy to override a class in a library installed with Composer

前端 未结 4 1896
抹茶落季
抹茶落季 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:19

    Changing an existing class is against OOP and SOLID principles (Open to extension/Closed for modification principle specificaly). So the solution here is not to change the code directly, but to extend the code to add your functionnality.

    In an ideal world you should never change a piece of code that you don't own. In fact, with composer you can't because your change will be overrided when updating dependencies.

    A solution in your case is to create a class at the application level, and extend the class you want to change (which is at the library level) to override with your code. Please look at extending a class in PHP if you don't know how.

    Then typically, you load your class instead of their class, this way, you add your functionnality on top of their functionnality, and in case of an update, nothing break (in case of a non breaking update).

提交回复
热议问题