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
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.
You can't chain directly from the class instantiation:
$Mail = new MailClass("mail")
->SetFrom("X")
->SetTo("Y");
you have to instantiate first, then chain against the instantiated object:
$Mail = new MailClass("mail") ;
$Mail->SetFrom("X")
->SetTo("Y");
If you validate within the individual setter methods (as you should) then you need to ensure that you throw exceptions when a validation error is encountered. You can't simply return a boolean false on error, otherwise the chaining will try to call the next method against a boolean rather than you class instance and you'll get.
Fatal error: Call to a member function SetSubject() on a non-object in C:\xampp\htdocs\oChainTest.php on line 23
if you throw exceptions, you can wrap the chain within try... catch
$Mail = new MailClass("mail");
try {
$Mail->SetFrom("X")
->SetTo("Y")
->SetSubject("Z");
} catch (Exception $e) {
echo $e->getMessage();
}
but as a warning, this will leave the instance in a partially updated state, there's no rollback (unless you write one yourself) for the methods that did validate/execute successfully, and the methods following the exception won't be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With