Giter Site home page Giter Site logo

design-patterns-php's Introduction

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)

design-patterns-php's People

Contributors

a1812 avatar denisvmedia avatar jacyimp avatar lex111 avatar nadim1992 avatar neochief avatar reducibly avatar smkoyan avatar vartob avatar wtig avatar xxhsu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

design-patterns-php's Issues

Rewrite real examples to PHP 8.2

Hi, PHP 8.2 is the current version, and PHP 8.3 will come faster than we all think, therefore I want to start a new discussion, whether we should rewrite code samples to PHP 8.2 and start using "constructor property promotion" or not. What do you think about it?

Example Adapter code with constructor property promotion:

/**
 * EN: The Adapter is a class that links the Target interface and the Adaptee
 * class. In this case, it allows the application to send notifications using
 * Slack API.
 *
 * RU: Адаптер – класс, который связывает Целевой интерфейс и Адаптируемый
 * класс. Это позволяет приложению использовать Slack API для отправки
 * уведомлений.
 */
class SlackNotification implements Notification
{
    public function __construct(private readonly SlackApi $slack, private readonly string $chatId)
    {
    }

    /**
     * EN: An Adapter is not only capable of adapting interfaces, but it can
     * also convert incoming data to the format required by the Adaptee.
     *
     * RU: Адаптер способен адаптировать интерфейсы и преобразовывать входные
     * данные в формат, необходимый Адаптируемому классу.
     */
    public function send(string $title, string $message): void
    {
        $slackMessage = "#" . $title . "# " . strip_tags($message);
        $this->slack->logIn();
        $this->slack->sendMessage($this->chatId, $slackMessage);
    }
}

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 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.