Example of Factory Pattern in PHP

A guide on the Factory Pattern in PHP with a concrete example, explaining how to implement and use this design pattern in object-oriented programming.

The Factory pattern provides a way to create objects without having to specify the exact class that needs to be instantiated. This makes the code more flexible and easier to extend when different types of objects need to be created.

<?php
// Factory Pattern in PHP

// Interface for different types of products
interface Product {
    public function getType();
}

// Concrete product classes
class ProductA implements Product {
    public function getType() {
        return "Product A";
    }
}

class ProductB implements Product {
    public function getType() {
        return "Product B";
    }
}

// Factory to create product objects
class ProductFactory {
    public static function createProduct($type) {
        switch ($type) {
            case 'A':
                return new ProductA();
            case 'B':
                return new ProductB();
            default:
                throw new Exception("Product type not found.");
        }
    }
}

// Using the factory to create products
try {
    $productA = ProductFactory::createProduct('A');
    echo $productA->getType();  // Output: Product A

    $productB = ProductFactory::createProduct('B');
    echo $productB->getType();  // Output: Product B
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Detailed explanation:

  1. interface Product: This defines an interface for the products that the factory will create. Each product must implement the getType() method.

  2. class ProductA and class ProductB: These are concrete classes representing different types of products. Both classes implement the getType() method to return the product type.

  3. class ProductFactory: This is the factory class that contains the createProduct($type) method, which creates an object based on the $type parameter. If $type is 'A', it creates a ProductA object, and for 'B', it creates ProductB.

  4. ProductFactory::createProduct('A'): This call creates a ProductA object when 'A' is passed as the type.

  5. catch (Exception $e): This handles any exceptions in case the product type is invalid or does not exist.

PHP Version:

This code is compatible with PHP 5.0 and above.



Related

Multithreading in PHP using the pthreads library

A comprehensive guide on how to implement multithreading in PHP using the `pthreads` library. This article covers installation steps, examples, and how to use multithreading to improve PHP application performance.
Update data in MySQL with PHP using Prepared Statements to Prevent SQL Injection

Guide on using Prepared Statements in PHP to update data in MySQL securely and efficiently. This PHP code helps prevent SQL Injection vulnerabilities when working with databases.
How to check for a substring in a string in PHP

A guide on how to use the `strpos` function in PHP to check if a substring exists within a larger string. This is a simple and efficient way to handle string operations in PHP.
JSON Web Token (JWT) Authentication with PHP

A guide on using JSON Web Token (JWT) for authentication in PHP. Using JWT ensures secure transmission of information between client and server and is easy to implement in web applications.
Creating a Simple Chat Application Using Socket.IO in PHP

A step-by-step guide to creating a simple chat application using Socket.IO in PHP, helping you understand how to utilize WebSocket for real-time communication.
How to convert a Markdown string to HTML using PHP

A guide on how to convert a Markdown string to HTML in PHP using the `Parsedown` library, enabling you to display Markdown content effectively on your website.
Creating Captcha Code with PHP

A guide on how to create a simple Captcha using PHP to protect your website from spam and automated bots.
Difference between `split()` and `explode()` functions for String manipulation in PHP

This article explains the difference between `split()` and `explode()` functions in PHP, both used to split strings but with different approaches and use cases.
How to remove Punctuation from String in PHP

A guide on how to remove punctuation from a string in PHP. This article explains how to use the `preg_replace` function to strip unwanted punctuation marks from a string.
How to retrieve Data from MySQL Database Using PHP

Learn how to retrieve data from a MySQL database using PHP. Includes detailed code and explanation on how to connect to and query a MySQL database.

main.add_cart_success