简体   繁体   English

php覆盖供应商包类方法

[英]php override vendor package class method

What is the proper way to change a package installed through composer in the vendor folder. 在vendor文件夹中更改通过composer安装的包的正确方法是什么。

A: copy the package directory to the project source (so it is not changed by composer anymore) and use it from there. 答:将包目录复制到项目源(因此不再由作曲家更改)并从那里使用它。

B: Extend the class. B:扩展课程。

I would think that B is the proper way, but i see two problems with it. 我认为B是正确的方式,但我发现它有两个问题。 1. The extended class may not be compatible with an updated baseclass from the vendor directory. 1.扩展类可能与供应商目录中更新的基类不兼容。 (after "composer update") 2. How do I manipulate a method way down in the class chain. (在“作曲家更新”之后)2。如何在类链中操纵方法。

$classA = new ClassA();
$classB = $classA->getsomeOtherClassInstance();
$classB->methodToChange();

Ie I would have to change class A and B to make sure that the extended version of B is called. 即我必须更改A类和B类以确保调用B的扩展版本。

  1. The extended class may not be compatible with an updated baseclass from the vendor directory. 扩展类可能与供应商目录中更新的基类不兼容。 (after "composer update") (在“作曲家更新”之后)

The class should always be backwards compatible if you choose the correct version number in your composer.json file. 如果在composer.json文件中选择正确的版本号,则该类应始终向后兼容。 Take a look at https://getcomposer.org/doc/articles/versions.md (Keep in mind this only applies for code repositories that promise backwards compatibility, but most big names do.) 请看一下https://getcomposer.org/doc/articles/versions.md (请记住,这仅适用于承诺向后兼容的代码存储库,但大多数知名人士都这样做。)

Also, if you want you can choose a concrete version like for example '3.7.7' which would prevent composer update from updating your code, will always use that version. 此外,如果您希望您可以选择具体版本,例如“3.7.7”,这将阻止编写器更新更新您的代码,将始终使用该版本。 But better to do the above. 但更好的做到以上。

  1. How do I manipulate a method way down in the class chain. 如何在类链中操作方法。

If it is a private method then you were not meant to change it, better to look for its caller and override that method and class instead. 如果它是一个私有方法,那么你不是要改变它,更好地寻找它的调用者并改写该方法和类。 Also, take a look at Decorator design pattern it allows you to change behavior of methods dynamically on the fly. 另外,看看Decorator设计模式,它允许您动态地动态更改方法的行为。

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

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