0

I have the below class in a 3rd party library which I am not supposed to modify.

<?php

class MyMailer {
    public function send() {
        $mail = new PHPMailer();

        $mail->setFrom('from@example.com', 'Your Name');
        $mail->addAddress('myfriend@example.net', 'My Friend');
        $mail->Subject = 'First PHPMailer Message';
        $mail->Body = 'Hi! This is my first e-mail sent through PHPMailer.';

        $mail->Send();
    }

    public function check(){
        //code
    }
}

How can I override or hook the send() method or how can I override the entire class MyMailer with my own new class?

The below link suggests to use runKit which is not bundled with PHP by default. So there is no guarantee that it's all available in all my servers. I learnt that this approach is called Monkey Patching.

All the answers are very old and I wish if there are any new solution available.

Community
  • 1
  • 1
Purus
  • 5,701
  • 9
  • 50
  • 89
  • Could you not extend the class and add a `send` method to the new child class which doesn't call `parent::send()` ? It won't work if your code requires instantiating the base `MyMailer` though... – CD001 Feb 23 '17 at 09:22
  • @CD001: Lot of external libraries use this method and I can not edit them to use the extended class. – Purus Feb 23 '17 at 09:24
  • No, the extended class would be yours to do with whatever you want – RiggsFolly Feb 23 '17 at 09:26
  • I understand. But I want all 3rd party library classes to use my extended class? I don't have control on those external libs. Changing those libs are not possilbe as it will create problem during updates. – Purus Feb 23 '17 at 09:29

1 Answers1

1

The Patchwork library is so easy and I make it work with few tries.

http://patchwork2.org/

  1. Monekey patch any internal and other methods.
  2. Easy to use.
Purus
  • 5,701
  • 9
  • 50
  • 89