• Design pattern(Factory Method) in PHP

    Design Patterns

    There are numerous ways to structure the code and project for you web application, and you can put as much or as little thought as you like into architecting. But it is usually a good idea to follow to common patterns because it will make your code easier to manage and easier for others to understand.

    Factory

    Definition: “The Factory Method pattern is a design pattern used to define a runtime interface for creating an object. It’s called a factory because it creates various types of objects without necessarily knowing what kind of object it creates or how to create it.”

    One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the object you want to use. Consider the following example of the factory pattern:

    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
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    
    class Automobile
     
    {
     
        private $vehicle_make;
     
        private $vehicle_model;
     
        public function __construct($make, $model)
     
        {
     
            $this->vehicle_make = $make;
     
            $this->vehicle_model = $model;
     
        }
     
        public function get_make_and_model()
     
        {
     
            return $this->vehicle_make . ' ' . $this->vehicle_model;
     
        }
     
    }
     
    class AutomobileFactory
     
    {
     
        public static function create($make, $model)
     
        {
     
            return new Automobile($make, $model);
     
        }
     
    }
     
    // have the factory create the Automobile object
     
    $veyron = AutomobileFactory::create('Bugatti', 'Veyron');
     
    print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron"

    This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way, the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead of repeating it every time you want to create a new instance.

    Using the factory pattern isn’t always necessary (or wise). The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save yourself a lot of trouble down the road by using factories.

Comments on this post

Leave a Reply

  • Security Code :


    × seven = 49