M
M
Maxim2018-06-18 02:20:33
Yii
Maxim, 2018-06-18 02:20:33

Yii How to avoid duplicate methods in classes?

Hello! There is a question connected with duplication of methods in classes.
There are several classes, let's say their name:
- Profile
- Price
- Post
They have the same constants and the same methods:

//Статусы
   const STATUS_NOT_PAID = 0;
    const STATUS_PAID = 1;
    const STATUS_CANCEL = 3;

and the methods themselves:
/**
     * Статистический метод получения списка статусов
     * @return array
     */
    public static function getStatusList()
    {
        return [
            self::STATUS_NOT_PAID => 'Не оплачено',
            self::STATUS_PAID => 'Оплачено',
            self::STATUS_CANCEL => 'Отменена'
        ];
    }

    /**
     * Получение статуса из модели
     * @return mixed
     */
    public function getStatusName()
    {
       ArrayHelper::getValue(self::getStatusList(),$this->status);
    }

These methods and constants are duplicated from one class to another. Moreover, if something changes in the statuses, you will have to change everywhere where they are applied.
How in this case is it better to implement the same methods without duplication and convenient use in different classes?
You cannot inherit from the same class because the classes are different. Interfaces will only help to prevent mistakes, but will not help to get rid of duplication from class to class. I guess that should be used in behaviors and attached where needed.... Am I right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DieZz, 2018-06-18
@myks92

As I see it, the most logical option is to make a separate class that will return the name of the status. It can be a helper, a component, or whatever, depending on the specifics of your business logic. for example

interface HasStatus
{
    public const STATUS_NOT_PAID = 0;
    public const STATUS_PAID     = 1;
    public const STATUS_CANCEL   = 3;

    public function getStatus(): int;
}

class StatusHelper
{
    /**
     * Статистический метод получения списка статусов
     *
     * @return array
     */
    public static function getStatusList()
    {
        return [
            HasStatus::STATUS_NOT_PAID => 'Не оплачено',
            HasStatus::STATUS_PAID     => 'Оплачено',
            HasStatus::STATUS_CANCEL   => 'Отменена',
        ];
    }

    public function getStatusName(HasStatus $entity): string
    {
        ArrayHelper::getValue(self::getStatusList(), $entity->getStatus());
    }
}

Accordingly, all your models must implement the HasStatus interface. Thus, all business logic is in one place and decoupled from the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question