NYCPHP Meetup

NYPHP.org

[nycphp-talk] OOP noob - general best practices

Chris Snyder chsnyder at gmail.com
Wed Jan 20 11:05:32 EST 2010


On Wed, Jan 20, 2010 at 9:39 AM, Yitzchak Schaffer
<yitzchak.schaffer at gmx.com> wrote:
>
> When should one use a factory method
> $foo = Foo::factory( $this )
> as opposed to using the constructor in the client code
> $foo = new Foo( $this )
> ?

The static factory pattern has always bugged me. I suspect it is much
more useful in other languages than in PHP.

There is sometimes a need for a factory class, which can make
instances of class that all share one or more resources:

$fooFactory = new fooFactory( $resource );
$foo1 = $fooFactory->newFoo();
$foo2 = $fooFactory->newFoo();


> And as corollary, what belongs in a constructor and what doesn't?  In
> http://www.slideshare.net/sebastian_bergmann/introduction-to-phpunit-best-practices
> slides 19-22, Sebastian Bergmann of PHPUnit alludes to this question, but in
> that presentation is apparently assuming the audience is familiar with the
> answer, and doesn't go into it; his tagline is "don't do work in the
> constructor," but rather do something like the following.  I don't know what
> does and does not constitute "work."
>
> $foo = new Foo( $this );
> $foo->build();

I think the advantage you get is that you can call build() at other
times to "rebuild" the object, and if you extend the class you could
do something else before the build() method is called.

In PHP it has the extra advantage that if you have no constructor you
don't need to decide what to name it (Foo() or __construct() ?).

But it also means that you have to add an additional line to your
operational code every time you want a new Foo, which could get
annoying if you use that class a lot.



More information about the talk mailing list