How to use the Abstract Factory design pattern in PHP to create related objects?

Member

by deron , in category: PHP General , a year ago

How to use the Abstract Factory design pattern in PHP to create related objects?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , a year ago

@deron 

The Abstract Factory design pattern is a creational design pattern that allows you to create related objects without specifying their concrete classes. In PHP, you can implement this pattern by creating an abstract factory class and concrete factory classes that inherit from it. Here's an example:


First, create an abstract factory class that defines the interface for creating related objects:

1
2
3
4
5
6
7
<?php

abstract class AbstractFactory
{
    abstract public function createProductA(): ProductA;
    abstract public function createProductB(): ProductB;
}


Next, create concrete factory classes that inherit from the abstract factory class and implement the create methods for each related object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php

class ConcreteFactory1 extends AbstractFactory
{
    public function createProductA(): ProductA
    {
        return new ConcreteProductA1();
    }

    public function createProductB(): ProductB
    {
        return new ConcreteProductB1();
    }
}

class ConcreteFactory2 extends AbstractFactory
{
    public function createProductA(): ProductA
    {
        return new ConcreteProductA2();
    }

    public function createProductB(): ProductB
    {
        return new ConcreteProductB2();
    }
}


Finally, create product classes that are created by the concrete factory classes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

interface ProductA {}

interface ProductB {}

class ConcreteProductA1 implements ProductA {}

class ConcreteProductB1 implements ProductB {}

class ConcreteProductA2 implements ProductA {}

class ConcreteProductB2 implements ProductB {}


To use the abstract factory pattern, simply instantiate the appropriate concrete factory class and use its create methods to create related objects:

1
2
3
4
5
6
7
8
9
<?php

$factory1 = new ConcreteFactory1();
$productA1 = $factory1->createProductA();
$productB1 = $factory1->createProductB();

$factory2 = new ConcreteFactory2();
$productA2 = $factory2->createProductA();
$productB2 = $factory2->createProductB();


In this example, the concrete factory classes (ConcreteFactory1 and ConcreteFactory2) are responsible for creating related objects (ConcreteProductA1, ConcreteProductB1, ConcreteProductA2, and ConcreteProductB2) without exposing their concrete classes.