Page 1 of 1
Purpose of newInstance methods
Posted: Mon Apr 27, 2009 10:22 am
by kAlvaro
I'm new to Swift Mailer but I've faced no problems so far (docs are really good).
Just curious about something... Why Swift_SmtpTransport::newInstance('example.com', 25) rather than good old new Swift_SmtpTransport('example.com', 25)? Is it a compatibility hack for PHP 4 or something like that?
Re: Purpose of newInstance methods
Posted: Mon Apr 27, 2009 1:24 pm
by AlexC
It allows you to do method chaining from the start, i.e:
Code: Select all
<?php
$foo = new Foo()->bar(); // Parse error
$foo = Foo::newInstance()->bar() // Will work just fine
?>
To do it without the static newInstance, you'd need to do:
Code: Select all
<?php
$foo = new Foo;
$foo->bar();
?>
Edit: Swift Mailer 4 is also PHP 5 only, btw
Re: Purpose of newInstance methods
Posted: Tue Apr 28, 2009 2:12 am
by kAlvaro
Ah, it's a clever trick indeed. Thank you.
Re: Purpose of newInstance methods
Posted: Sat May 02, 2009 5:51 am
by Chris Corbyn
Having the newInstance() methods also allows me some room to change the way the class is actually instantiated. It's a common design pattern called the Factory Pattern.
It's not documented, but you can use new ClassName() in place of the newInstance() method. The reason it's not documented is because at some point in the future I may make the constructor of some classes private/protected as part of a refactoring exercise.