Answer the question
In order to leave comments, you need to log in
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;
/**
* Статистический метод получения списка статусов
* @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);
}
Answer the question
In order to leave comments, you need to log in
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());
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question