Search code examples
phpobjectfluent-interfacechaining

Effects of method chaining


I know the benefits of chaining within PHP but lets say we have this following situation

$Mail = new MailClass("mail")
        ->SetFrom("X")
        ->SetTo("X")
        ->SetSubject("X")
        ->AddRecipient("X")
        ->AddRecipient("X")
        ->AddRecipient("X")
        ->AddRecipient("X")
        ->AddRecipient("X")
        ->AddRecipient("X")
        ->Send();

Are there any issues with returning and reusing the object over and over again, issues such as speed or failure to follow best Practises

Also a good read on this if your new to Fluent-Interface's: Martin Fowler on Fluent-Interfaces

I Fully understand that it doesn't have to be programmed this way, and can be handled like so:

$Mail = new MailClass("mail");
$Mail->AddRecipien(
    array(/*.....*/)
);
$Mail->SetFrom("X");
$Mail->SetTo("X");
$Mail->SetSubject("X");
$Mail->Send();

but lets say I have an object like so:

$Order = new Order()
         ->With(22,'TAL')
         ->With(38,'HPK')->Skippable()
         ->With(2,'LGV')
         ->Priority();

Note the ->With(38,'HPK')->Skippable(), This is perfect example of a Pro for this type of programming


Solution

  • If you have to validate Something, i think it makes more sense to validate it in the AddRecipient Method itself, but the Performance should be about the same. And I'm not aware of any general disadvantages of using method chaining.