antecedent / patchwork
Method redefinition (monkey-patching) functionality for PHP.
Installs: 7 251 323
Dependents: 33
Suggesters: 0
Security: 0
Stars: 421
Watchers: 14
Forks: 43
Open Issues: 21
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: >=4
- dev-master
- 2.1.25
- 2.1.24
- 2.1.23
- 2.1.22
- 2.1.21
- 2.1.20
- 2.1.19
- 2.1.18
- 2.1.17
- 2.1.16
- 2.1.15
- 2.1.14
- 2.1.13
- 2.1.12
- 2.1.11
- 2.1.10
- 2.1.9
- 2.1.8
- 2.1.7
- 2.1.6
- 2.1.5
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.9
- 2.0.8
- 2.0.7
- 2.0.6
- 2.0.5
- 2.0.4
- 2.0.3
- 2.0.2
- 2.0.1
- 2.0.0
- 1.4.3
- 1.4.2
- 1.4.1
- 1.4.0
- 1.3.5
- 1.3.4
- 1.3.2
- 1.3.1
- 1.3.0
- 1.2.9
- 1.2.8
- 1.2.7
- 1.2.6
- dev-void-typed-bug
- dev-readme
- dev-redefinition-of-new
- dev-interception-of-language-constructs
- dev-redefinition-of-internals
This package is auto-updated.
Last update: 2023-05-20 09:36:45 UTC
README
Patchwork implements the redefinition (monkey-patching) of user-defined methods in PHP.
Internally, it uses a stream wrapper on file://
to inject a simple interceptor snippet to the beginning of every method.
Example: a DIY profiler
use function Patchwork\{redefine, relay, getMethod}; $profiling = fopen('profiling.csv', 'w'); redefine('App\*', function(...$args) use ($profiling) { $begin = microtime(true); relay(); # calls the original definition $end = microtime(true); fputcsv($profiling, [getMethod(), $end - $begin]); });
Notes
- Method redefinition is the internally preferred metaphor for Patchwork's behavior.
restoreAll()
andrestore($handle)
end the lifetime of, respectively, all redefinitions, or only one of them, where$handle = redefine(...)
.- Closure
$this
is automatically re-bound to the enclosing class of the method being redefined. - The behavior of
__CLASS__
,static::class
etc. inside redefinitions disregards the metaphor.getClass()
,getCalledClass()
,getMethod()
andgetFunction()
from thePatchwork
namespace should be used instead.
Testing-related uses
Patchwork can be used to stub static methods, which, however, is a controversial practice.
It should be applied prudently, that is, only after making oneself familiar with its pitfalls and temptations in other programming languages. For instance, in Javascript, Ruby, Python and some others, the native support for monkey-patching has made its testing-related uses more commonplace than in PHP.
Tests that use monkey-patching are no longer unit tests, because they become sensitive to details of implementation, not only those of interface: for example, such a test might no longer pass after switching from time()
to DateTime
.
That being said, they still have their place where the only economically viable alternative is having no tests at all.
Other use cases
The current version of Patchwork is not suggested for AOP and other kinds of production usage. The next one will switch from stream wrappers to stream filters, which will ensure interoperability with opcode caches.