RefactoringGuru / design-patterns-php

Design Pattern Examples in PHP

Home Page:https://refactoring.guru/design-patterns/php

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rewrite real examples to PHP 8.2

piotrfilipek opened this issue · comments

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);
    }
}

To be frank with you, I think the original version is more obvious. However, I might simply need some time getting used to the new syntax. Btw, maybe breaking down the parameters into multiple lines would help, but I'm not sure whether this is allowed per coding convention.

P.S. Sorry, I forgot to thank you for the offer. I appreciate it very much, but I'm on the fence whether we should do this particular change at the moment.

Btw, maybe breaking down the parameters into multiple lines would help, but I'm not sure whether this is allowed per coding convention.

Yes, it's allowed and it looks like the code below:

class SlackNotification implements Notification
{
    public function __construct(
        private readonly SlackApi $slack,
        private readonly string $chatId
    ) {
    }

    public function send(string $title, string $message): void
    {
        $slackMessage = "#" . $title . "# " . strip_tags($message);
        $this->slack->logIn();
        $this->slack->sendMessage($this->chatId, $slackMessage);
    }
}

P.S. Sorry, I forgot to thank you for the offer. I appreciate it very much, but I'm on the fence whether we should do this particular change at the moment.

Sure, no problem. If you'll ready to make some changes, then we can continue this thread :)