← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 9 of 24

PHP Design Patterns

Design patterns common coding puzzles के tried-and-true solutions हैं, well-known recipes जैसे। इन्हें इस्तेमाल करना दूसरे programmers को जल्दी पहचानने में मदद करता है कि आपका code कैसे organized है।

Design Patterns क्या हैं?

Design patterns recurring design problems के named, battle-tested solutions हैं -- वे developers को एक shared vocabulary देते हैं ('यहाँ बस एक Factory इस्तेमाल करो') बजाय सबके independently similar structures reinvent करने के।

उदाहरण: What are Design Patterns?

php
<?php
// Print "A named, reusable solution to a recurring design problem -- like 'use a Factory here'" to the output
echo "A named, reusable solution to a recurring design problem -- like 'use a Factory here'";
?>

Singleton Pattern

Singleton pattern guarantee करता है कि एक class सिर्फ कभी एक बार instantiate हो सकती है और उस instance तक एक single global access point expose करता है, आमतौर पर एक shared database connection जैसी चीज़ों के लिए इस्तेमाल होता है।

उदाहरण: The Singleton Pattern

php
<?php
// Define the class `Database`
class Database {
    // Declare the private static property `$instance`, set to `null`
    private static $instance = null;
    // Define the constructor `__construct` with no parameters
    private function __construct() {}
    // Define the function `getInstance` with no parameters
    static function getInstance() {
        // Check whether `self::$instance === null`
        if (self::$instance === null) {
            self::$instance = new self();
        }
        // Return `self::$instance` from this function
        return self::$instance;
    }
}
// Declare `$db1`, set to `Database::getInstance()`
$db1 = Database::getInstance();
// Declare `$db2`, set to `Database::getInstance()`
$db2 = Database::getInstance();
// Print a detailed dump (with types) of `$db1 === $db2`
var_dump($db1 === $db2);
?>

Factory Pattern

Factory pattern object creation को एक dedicated method या class के पीछे छुपाता है, ताकि calling code 'एक Shape' माँगे बिना यह जाने कि उसे एक Circle या एक Square मिलेगा -- तब उपयोगी जब creation logic complex हो या input के हिसाब से vary करे।

उदाहरण: The Factory Pattern

php
<?php
// Define the interface `Shape` describing required methods
interface Shape {
    // Define the function `draw` with no parameters
    function draw();
}
// Define the class `Circle`, implementing `Shape`
class Circle implements Shape {
    // Define the function `draw` with no parameters
    function draw() { echo "Drawing a circle"; }
}
// Define the class `ShapeFactory`
class ShapeFactory {
    // Define the function `create` taking `$type`
    static function create($type) {
        if ($type === "circle") return new Circle();
    }
}
// Declare `$shape`, set to `ShapeFactory::create("circle")`
$shape = ShapeFactory::create("circle");
$shape->draw();
?>

Observer Pattern

Observer pattern एक subject object को उसकी state बदलते ही registered observer objects की एक list को notify करने देता है, जो ज़्यादातर event-listener और pub-sub systems के पीछे की foundation है।

उदाहरण: The Observer Pattern

php
<?php
// Define the class `Subject`
class Subject {
    // Declare the private property `$observers`, set to `[]`
    private $observers = [];
    // Define the function `subscribe` taking `$observer`
    function subscribe($observer) {
        $this->observers[] = $observer;
    }
    // Define the function `notify` taking `$event`
    function notify($event) {
        // Loop over `$this->observers`, binding each item to `$observer`
        foreach ($this->observers as $observer) {
            $observer($event);
        }
    }
}
// Create a new `Subject` instance, stored in `$subject`
$subject = new Subject();
$subject->subscribe(function ($event) {
    // Print "Observer received: $event" to the output
    echo "Observer received: $event";
});
$subject->notify("state changed");
?>

Patterns के लिए Best Practices

Patterns real problems solve करते हैं लेकिन indirection add करते हैं -- एक five-line script पर एक Factory या Observer apply करना बिना किसी benefit के complexity add करता है, इसलिए किसी pattern तक तभी जाएँ जब किसी project की genuine needs इसे justify करें।

उदाहरण: Best Practices for Patterns

php
<?php
// A five-line script doesn't need a Factory or Observer -- that's added complexity with no benefit
function greet() {
    echo "Hello!";
}
greet();
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. जहाँ एक simple function काम कर जाता वहाँ एक design pattern apply करना, जो सिर्फ complexity add करता है।
  2. हर चीज़ के लिए Singleton इस्तेमाल करना, जो hidden global state बनाता है जिसे test करना मुश्किल है।
  3. classes को एक-दूसरे पर directly depend करवाना, जो Observer जैसे patterns का purpose defeat कर देता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.