tags:

views:

100

answers:

3

Hi

I just want to know that what is the factory in php?

And how can I use it in my code?

Are there and benefits and drawbacks of it?

Thanks
Avinash

+1  A: 

It's a function that creates classes. If you need to bulk-create classes with minor variations in behavior then it's useful. On the other hand, abuse leads to things like FactoryFactoryFactoryFactoryFactoryFactory.

Ignacio Vazquez-Abrams
+1  A: 

An AbstractFactory is a Creational Design Pattern, that

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

In a nutshell:

class MercedesFactory
{
    public static function createCar()
    {
        $engine = new MercedesEngine;
        $car = new Mercedes($engine);
        return $car;
    }
}

There is also the Factory Method, which

Defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

In a nutshell:

class User
{
    public static function create()
    {
        return new self;
    }
}
Gordon
+2  A: 

Factory is one of the most useful patterns, because it provides a way to remove specific class names from the code, making it easier to support and refactor.

Consider an example: you've got an application that sends emails and uses 'Mailer' class for this purpose:

class Site

  function sendWelcomeMail
     $m = new Mailer;
     $m->send("Welcome..."); 

  function sendReminderMail
     $m = new Mailer;
     $m->send("Reminder..."); 

 etc...

One day you decide to use another mailer class, called 'NewMailer'. With code like above you have to find all occurences of Mailer and replace them manually into NewMailer. This can be a real pain in a large project.

With a Factory you don't use 'new' and specific class names and just call a method when you need an object

class Factory

      function createMailer() 
          return new Mailer;


class Site

  function sendWelcomeMail
     $m = Factory::createMailer();
     $m->send("Welcome..."); 

  function sendReminderMail
     $m = Factory::createMailer();
     $m->send("Reminder..."); 

 etc...

To replace Mailer with NewMailer all over the place you just change one single line in the factory method.

stereofrog
Though you should add that exchanging a `new Foo` for a `FooFactory::create` is still a hardcoded and implicit dependency. Both is hard to unit-test.
Gordon