Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Monkey patch PHP classes with the BetterReflection Library

Link –

At the PHP Benelux conference James Titcumb did a presentation on the BetterReflection library he's working on. You can view the slides of his presentation on SlideShare.

The BetterReflection library has a few advantages over PHP's native reflection capabilities (copied from the docs):

  • you can reflect on classes that are not already loaded, without loading them
  • ability to reflect on classes directly from a string of PHP code
  • better Reflection analyses the DocBlocks (using phpdocumentor/type-resolver)
  • reflecting directly on closures
When this pull request will get merged the library even makes it possible to monkey patch classes. Let's take a look how you would do that.

Consider this class:

class MonkeyPatchMe
{
    function getMessage() : string
    {
        return 'hello everybody';
    }
}

The body of the getMessage-function can be replaced using this code:

$classInfo = ReflectionClass::createFromName('MonkeyPatchMe');

$methodInfo = $classInfo->getMethod('getMessage');

$methodInfo->setBody(function() {
   return 'bye everybody';
});

$monkeyPatchedClass = new MonkeyPatchMe();
$monkeyPatchedClass->getMessage() // returns 'bye everybody'


Behind the scenes this voodoo works by copying the original class to another file, doing a replacement of the function body there and loading up that class.

I'll be keeping my eye on how the BetterReflection library evolves. You can read all about it's current functionality in the docs on GitHub.

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "Monkey patch PHP classes with the BetterReflection Library"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.