Answer the question
In order to leave comments, you need to log in
What is the correct way to implement many small classes with similar functionality and one parent?
The formulation of such a question was not such a simple thing.
Problem: There is a certain numeric parameter that needs to be formatted in many ways. The user needs to be given a choice of formatting type with the output of its name.
Sounds confusing. I was trying to make one class a parent that implements the format($value) method.
And a lot of descendant classes, each of which offers its own implementation of the format method and which has a field for formatting description. But I ran into the problem of automatically loading all these classes (there will be two dozen of them, no less). And the unification of the formatting method call.
Case: The user entered a number. I have to give him a list of all the formatting methods that are available. For example:
1. Cut off 1 character ahead.
2. Multiply by 10.
and so on.
When choosing a method, it must be applied to a number.
Please tell me the best solution for the problem.
Answer the question
In order to leave comments, you need to log in
class NumberManager
{
/**
* Форматирование чисел
* @param integer $number Число
* @param string $formatClass Класс для форматирования
* @param array $formatClassParams Параметры для класса форматирования
* return bool
*/
public function format($number, $formatClass, $formatClassParams = [])
{
// Создаём экземляр класса для форматирования
$formatClassName = $formatClass . 'Format';
if (!class_exists($formatClassName)) {
return false;
}
$formatter = new $formatClass();
// Передаём этому классу число, параметры форматирования и получаем результат
return $formatter->formatNumber($number, $formatClassParams);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question