What is a Factory Design Pattern in PHP?
Asked Answered
T

11

116

This confuses me, in the most simplest terms what does it do? Pretend you are explaining to your mother or someone almost please.

Trussing answered 18/1, 2010 at 1:28 Comment(3)
My mother wouldn't understand it anyway...Bridgers
@Trussing I keep answering your questions... I'm beginning to feel like a stalker.Puppis
You order a car, it gets to your door assembled while the assembly has been done in a factory somewhere. In programming, when you instantiate a factory, it should deliver the functionality without the need of instantiating inner concrete functionalityies.Dona
P
199

A factory creates an object. So, if you wanted to build

 class A{
    public $classb;
    public $classc;
    public function __construct($classb, $classc)
    {
         $this->classb = $classb;
         $this->classc = $classc;
    }
  }

You wouldn't want to rely on having to do the following code everytime you create the object

$obj = new ClassA(new ClassB, new Class C);

That is where the factory would come in. We define a factory to take care of that for us:

class Factory{
    public function build()
    {
        $classc = $this->buildC();
        $classb = $this->buildB();
        return $this->buildA($classb, $classc);

    }

    public function buildA($classb, $classc)
    {
        return new ClassA($classb, $classc);
    }

    public function buildB()
    {
        return new ClassB;
    }

    public function buildC()
    {
        return new ClassC;
    }
}

Now all we have to do is

$factory = new Factory;
$obj     = $factory->build();

The real advantage is when you want to change the class. Lets say we wanted to pass in a different ClassC:

class Factory_New extends Factory{
    public function buildC(){
        return new ClassD;
    }
}

or a new ClassB:

class Factory_New2 extends Factory{
    public function buildB(){
        return new ClassE;
    }
}

Now we can use inheritance to easily modify how the class is created, to put in a different set of classes.

A good example might be this user class:

class User{
    public $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
}

In this class $data is the class we use to store our data. Now for this class, lets say we use a Session to store our data. The factory would look like this:

class Factory{
    public function build()
    {
        $data = $this->buildData();
        return $this->buildUser($data);
    }

    public function buildData()
    {
        return SessionObject();
    }

    public function buildUser($data)
    {
        return User($data);
    }
}

Now, lets say instead we want to store all of our data in the database, it is really simple to change it:

class Factory_New extends Factory{
    public function buildData()
    {
        return DatabaseObject();
    }
}

Factories are a design pattern we use to control how we put objects together, and using correct factory patterns allows us to create the customized objects we need.

Puppis answered 18/1, 2010 at 1:37 Comment(4)
That was a lot of typing. Now I will have to put it on my wiki at some point.Puppis
Nice and helpful. Hats off to you mate.Frenulum
What is the difference/benefit of your code $obj = $factory->build(); over $obj = new whateverClass();? Also, in another class (say classZ) which depends on classA's data, where in classZ would you use the factory method? You're essentially still instantiating a class (classZ) within a class (classA), which means no testing. e.g. the factory just seems to be a load of code to do new via a method instead of just using new.Protecting
This is confusing for me. I've been reading about factories and builders for the past hour and this seems like a builder, not factory.Fovea
P
52

Factory design pattern is very good when you are dealing with multiple resources and want to implement high level abstraction.

Let's break this into different section.

Suppose you have to implement abstraction and the user of your class doesn't need to care about what you've implemented in class definition.

He/She just need to worry about the use of your class methods.

e.g. You have two databases for your project

class MySQLConn {

        public function __construct() {
                echo "MySQL Database Connection" . PHP_EOL;
        }

        public function select() {
                echo "Your mysql select query execute here" . PHP_EOL;
        }

}

class OracleConn {

        public function __construct() {
                echo "Oracle Database Connection" . PHP_EOL;
        }

        public function select() {
                echo "Your oracle select query execute here" . PHP_EOL;
        }

}

Your Factory class would take care of the creation of object for database connection.

class DBFactory {

        public static function getConn($dbtype) {

                switch($dbtype) {
                        case "MySQL":
                                $dbobj = new MySQLConn();
                                break;
                        case "Oracle":
                                $dbobj = new OracleConn();
                                break;
                        default:
                                $dbobj = new MySQLConn();
                                break;
                }

                return $dbobj;
        }

}

User just need to pass the name of the database type

$dbconn1 = DBFactory::getConn("MySQL");
$dbconn1->select();

Output:

MySQL Database Connection
Your mysql select query execute here

In future you may have different database then you don't need to change the entire code only need to pass the new database type and other code will run without making any changes.

$dbconn2 = DBFactory::getConn("Oracle");
$dbconn2->select();

Output:

Oracle Database Connection
Your oracle select query execute here

Hope this will help.

Possibly answered 25/4, 2018 at 6:28 Comment(2)
i think this is the best solutionRelique
Good example that I understood instantly. Thank you.Disraeli
Y
22

Like a real life factory, it creates something and returns it.

Imagine something like this

$joe = new Joe();
$joe->say('hello');

or a factory method

Joe::Factory()->say('hello');

The implementation of the factory method will create a new instance and return it.

Yerkovich answered 18/1, 2010 at 1:31 Comment(2)
Nice example, amazes me how varied the implementations are for this pattern. When called statically, I assume one can one get a reference to the instance to reuse same instance later on? ie $joe = Joe::Factory()->say('hello');Frenulum
certainly as at 5.6 one can also do (new Joe())->say('hello');Peel
P
3

The classic approach to instantiate an object is:

$Object=new ClassName();

PHP has the ability to dynamically create an object from variable name using the following syntax:

$Object=new $classname;

where variable $classname contains the name of class one wants to instantiate.

So classic object factoring would look like:

function getInstance($classname)
{
  if($classname==='Customer')
  {
    $Object=new Customer();
  }
  elseif($classname==='Product')
  {
    $Object=new Product();
  }
  return $Object;
}

and if you call getInstance('Product') function this factory will create and return Product object. Otherwise if you call getInstance('Customer') function this factory will create and return Customer type object (created from Customer() class).

There's no need for that any more, one can send 'Product' or 'Customer' (exact names of existing classes) as a value of variable for dynamic instantiation:

$classname='Product';
$Object1=new $classname; //this will instantiate new Product()

$classname='Customer';
$Object2=new $classname; //this will instantiate new Customer()
Plainspoken answered 14/9, 2014 at 12:41 Comment(0)
C
1

In general a "factory" produces something: in the case of Object-Orientated-Programming, a "factory design pattern" produces objects.

It doesn't matter if it's in PHP, C# or any other Object-Orientated language.

Celebrant answered 18/1, 2010 at 1:31 Comment(0)
I
1

Factory Design Pattern (Factory Pattern) is for loose coupling. Like the meaning of factory, data to a factory (produce data) to final user. By this way, the factory break the tight coupling between source of data and process of data.

Ireland answered 17/6, 2013 at 11:22 Comment(0)
H
0

A factory just generates an object or objects.

You may have a factory that builds a MySQL connection.

http://en.wikipedia.org/wiki/Factory_method_pattern

Hudnut answered 18/1, 2010 at 1:30 Comment(0)
M
0

This answer is in relation to other post in which Daniel White said to use factory for creating MySQL connection using factory pattern.

For MySQL connection I would rather use singleton pattern as you want to use same connection for accessing the database not create another one.

Monjo answered 9/4, 2014 at 13:30 Comment(0)
D
0

For the record, in easy words, a factory like @Pindatjuh said, returns a object.

So, what's the difference with a constructor? (that does the same)

  1. a constructor uses his own instance.
  2. Something i want to so something more advanced and i don't want to bloat the object (or add dependencies).
  3. Constructor is called when each instance is created. Sometimes you don't want that.

    For example, let's say that every time i creates an object of the class Account, i read from the database a file and use it as a template.

Using constructor:

class Account {
      var $user;
      var $pwd;
      var ...
      public __construct() {
         // here i read from the file
         // and many other stuff
      }
}

Using factory:

class Account {
      var $user;
      var $pwd;
      var ...
}
class AccountFactory {
      public static Create() {
         $obj=new Account();
         // here we read the file and more stuff.
         return $obj;
      }
Dowzall answered 26/3, 2016 at 21:33 Comment(0)
B
0

The factory is a solution for easy maintenance and scalability when it comes to your application code. It solves the code coupling issue that SOLID suggests we follow. Essentially is a way to simplify the build/creation of structures. It can be a object, a function, an array.

As long as you are decoupling code that uses the structure from code that creates them and returning objects/structures you are using a factory which can be one of the four :

  • Factory method
  • Abstract factory
  • Static factory
  • Simple factory

The main difference resides in the factory method and abstract factory.

One generates objects/structures from a list of well defined elements, the other generate the blueprints of objects with their own factoring strategies.

One generates concrete elements, the other generates types.

Beloved answered 7/2, 2021 at 22:24 Comment(0)
S
-1

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

Take a maximum of 30 mins and go through this link Factory Method

Thank me later.

Syllabus answered 10/4, 2022 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.