Design Pattern Examples in PHP

Overview

Design Patterns in PHP

This repository is part of the Refactoring.Guru project.

It contains PHP examples for all classic GoF design patterns.

Each pattern includes two examples:

  • Conceptual examples show the internal structure of patterns, including detailed comments.

  • RealWorld examples show how patterns can be used in real-world PHP applications.

Requirements

These examples require PHP 7.3 and newer, although they can be easily replicated in older versions of PHP.

This version provides explicit argument and return type declarations, which help to understand better some patterns' features that are not very obvious in dynamically typed language.

All examples can be launched via the command line, using the PHP executable as follows:

php src/Path-to-example/index.php

For the best experience, I recommend working with examples with these IDEs:

Roadmap

  • Memento: RealLife
  • State: RealLife

I'm out of decent ideas for real-world usages for these two in PHP apps. If you had used them in your project, feel free to suggest me an idea by posting an Issue.

FAQ

1. What is the Client Code?

Client means client of classes, defined as part of a pattern, which is merely a caller of the given methods or a user of the given classes. In other words, it's the part of your application's code that uses the pattern's classes.

2. I don't understand the roles you're referring to in RealWorld examples.

Take a look at the conceptual example first. There you'll find detailed descriptions of each class in a pattern, its role, and connection to other classes.

Contributor's Guide

I appreciate any help, whether it's a simple fix of a typo or a whole new example. Just make a fork, make your change and submit a pull request.

Here's a style guide which might help you to keep your changes consistent with the rest of the project's code:

  1. All code should match the PSR2 coding style guide

  2. Try to hard-wrap the code at 80th's character. It helps to list the code on the website without scrollbars.

  3. Examples should match following namespace convention: RefactoringGuru\{pattern-name}\{example-name}. For instance:

    <?php
    
    namespace RefactoringGuru\FactoryMethod\Example\Buttons;
    
    class Button {
    ...
  4. Aim to put all code within one file. Yes, I realize that it's not how it supposed to be done in production. However, it helps people to understand examples better, since all code fits into one screen.

  5. Comments may or may not have language tags in them, such as this:

    /**
     * EN: All products families have the same varieties (MacOS/Windows).
     *
     * This is a MacOS variant of a button.
     *
     * RU: Все семейства продуктов имеют одни и те же вариации (MacOS/Windows).
     *
     * Это вариант кнопки под MacOS.
     */

    This notation helps to keep the code in one place while allowing the website to generates separate versions of examples for all listed languages. Don't be scared and ignore the non-English part of such comments. If you want to change something in a comment like this, just do it. Even if you do it wrong, we'll tell you how to fix it during the Pull Request.

License

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.

Creative Commons License

Credits

Authors: Alexander Shvets (@neochief) and Alexey Pyltsyn (@lex111)

Comments
  • WIP: Adds Turkish Language Support

    WIP: Adds Turkish Language Support

    Adds Turkish Language Support for this repository.

    I created merge request early for asking owners about adding Turkish language.

    Any help is welcome :star:

    Thank you for this lovely repository :heart:

    opened by erayaydin 5
  • Replace abstract class to an interface in the Interpreter pattern

    Replace abstract class to an interface in the Interpreter pattern

    Hi!

    First of all thanks a lot for this great repository. I've found that here the abstract class AbstractExp only has an abstract method so it can be replaced to an interface.

    Thanks and let me know :)

    opened by xserrat 2
  • Visitor real-world example

    Visitor real-world example

    Hello!

    I think the Visitor real-world example could be more informative as to why this pattern exists.

    I couldn't understand why instead of this

    echo "Client: I can print a report for a whole company:\n\n";
    echo $company->accept($report);
    
    echo "\nClient: ...or just for a single department:\n\n";
    echo $techSupport->accept($report);
    

    We couldn't use this:

    echo "Client: I can print a report for a whole company:\n\n";
    echo $report->visitCompany($company);
    
    echo "\nClient: ...or just for a single department:\n\n";
    echo $report->visitDepartment($techSupport);
    

    I think something like this gets the message more across:

    echo "\nClient: ...or for different entities "
        . "such as an employee, a department, or the whole company:\n\n";
    $someEmployee = new Employee("Some employee", "operator", 35000);
    $differentEntities = [$someEmployee, $techSupport, $company];
    foreach ($differentEntities as $entity) {
        echo $entity->accept($report) . "\r\n";
    }
    

    The latter made it much clear to me why we'd need interfaces and the visitor pattern.

    opened by jacyimp 1
  • update RealWorld example of Builder pattern

    update RealWorld example of Builder pattern

    I think its better to repeat validation part instead of calling parent's method which does unnecessary steps beside validation. And also it confused me and I scrolled back to see for what purpose parent's method called.

    Overthinking: Maybe we can extract validation part into some AbstractQueryBuilder as they are not part of syntax and probably that constraints are same for all SQL dialects.

    opened by smkoyan 1
  • Memento pattern - getState method not defined into interface

    Memento pattern - getState method not defined into interface

    Hello, I have noticed one tricky thing in a conceptual example. Here is an interface:

    interface Memento
    {
        public function getName(): string;    
        public function getDate(): string;
    }
    

    and here is restore() method from originator:

    public function restore(Memento $memento): void
    {
        $this->state = $memento->getState();
        echo "Originator: My state has changed to: {$this->state}\n";
    }
    

    I don't really understand how we can call getState method if interface doesn't declare it ?

    opened by sukhoy94 1
the examples of head first object oriented analysis & design - in PHP

Head First object oriented analysis & design in (PHP) after cloning the repository, you have to install the project's dependancies by running the foll

Muhammed ElFeqy 3 Oct 16, 2021
Examples of some common design patterns implemented in php

What is a Design Pattern? Design patterns are typical solutions to common problems in software design. Each pattern is like a blueprint that you can c

Bakhtiyor Bahritidinov 4 Feb 11, 2022
Showing what's new in PHP 8 with examples and tests

#PHP 8 what's new with examples Showing what's new in PHP 8 with examples and tests. I believe that reading about the changes is not enough, so grab t

Grzegorz Bielski 1 Dec 14, 2022
Demo serverless applications, examples code snippets and resources for PHP

The Serverless LAMP stack Examples Code example Description AWS blog link 0.1-SimplePhpFunction A very simple implementation of a PHP Lambda function.

AWS Samples 303 Dec 20, 2022
PHP examples - Refactoring by Martin Fowler

Refatoração - segunda edição - Exemplos em PHP https://www.youtube.com/watch?v=TBHehDRuVCs Prefácio: Case de refatoração x entregas e prazos O que é r

Eduardo Lourenço 3 Jul 20, 2022
SERP Scraping API code examples for Python, PHP and Node.js

SERP Scraping API List of contents Introduction Authentication Google Baidu Bing Yandex Parameters Targets Languages License Introduction With our SER

Smartproxy 8 Nov 7, 2022
Custom code snippets and examples for SkyVerge-built WooCommerce extensions

SkyVerge WooCommerce Plugins Welcome to the wc-plugins-snippets repository! This repository stores code snippets related to SkyVerge WooCommerce plugi

SkyVerge 255 Nov 16, 2022
Wordpress Plugin Boilerplate but Powered with examples and a generator!

WordPress Plugin Boilerplate Powered WordPress Plugin Boilerplate Powered is a complete foundation for building your WordPress plugins following PSR-4

WordPress Plugin Boilerplate Powered 604 Dec 24, 2022
Mvc - Phalcon MVC Examples

Phalcon MVC Examples These are examples of MVC file structures you can employ using Phalcon >= 3.0.x For further documentation, check out the Phalcon

The Phalcon PHP Framework 804 Jan 3, 2023
Examples of the power of WordPress plugins that will wreck your site.

Examples of the power of WordPress plugins that will wreck your site.

Teemu Suoranta 4 Mar 2, 2022
Some Joomla! 4.x Web Services Api Examples and Experiments to raise the level of awareness of the huge potiental of Joomla! 4.x Web Services.

j4x-api-examples WHY? If you are a Joomla! developer or want to become a Joomla! developer there is a new resource for you The Official New Joomla! Ma

Mr Alexandre ELISÉ 11 Nov 29, 2022
Sitepackage for TYPO3 CMS that adheres to the recommended standards, maps all conceivable functional areas and contains examples for common use cases.

TYPO3 CMS Sitepackage This sitepackage sticks as closely as possible to the recommended standard and maps all conceivable functional areas. There are

Eric Bode 3 Dec 18, 2022
This is a Native PHP MVC. If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo.

Welcome to PHP-Native-MVC-Pattern ?? If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo. Work

null 2 Jun 6, 2022
YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic.

YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic. It is built based on the combination of ideas from the Yii framework and Laravel framework (yl).

Tan Nguyen 3 Jan 3, 2023
PHP implementation of circuit breaker pattern.

What is php-circuit-breaker A component helping you gracefully handle outages and timeouts of external services (usually remote, 3rd party services).

ArturEjsmont 169 Jul 28, 2022
PHP regexp pattern matching Unicode emojis

Emoji pattern This package provides regexp patterns to match Unicode emojis. All forms of emojis are matched, including: Single-character emoji ( ?? )

Incenteev 7 Nov 5, 2022
Easy Repository pattern for PHP Phalcon framework.

Phalcon Repositories Introduction Phalcon Repositories lets you easily build repositories for your Phalcon models, for both SQL and Mongo drivers. PHP

Michele Angioni 18 Oct 7, 2022
Implementação do Composite Pattern Utilizando PHP

Composite Pattern - PHP Implementação do Composite Pattern Utilizando PHP Descrição O Composite Pattern é um padrão de projeto estrutural que permite

Anglesson Araújo 1 Jan 2, 2022
Sample code for several design patterns in PHP 8

DesignPatternsPHP Read the Docs of DesignPatternsPHP or Download as PDF/Epub This is a collection of known design patterns and some sample codes on ho

null 21k Jan 5, 2023