A
A
Andrew2017-01-04 06:50:54
PHP
Andrew, 2017-01-04 06:50:54

What is the best way to organize the work of several classes under one head?

Hello. I am writing for myself a set of helpers for working with numbers, text, dates, and so on. Each entity (text, numbers) has a set of classes that are responsible for handling a particular situation. I want to combine them nicely.
Just for example:

class math {
  public function sum($a, $b){
    return (int)$a + (int)$b;
  }

  public function mod($a, $b) {
    return (int)$a % (int)$b;
  }

  public function div($a, $b) {
    return (int)$a / (int)$b;
  }
}

class math2 {
  public function sumf($a, $b){
    return (float)$a + (float)$b;
  }

  public function modf($a, $b) {
    return (float)$a % (float)$b;
  }

  public function divf($a, $b) {
    return (float)$a / (float)$b;
  }
}

I would like it to be something like this (approximately) (But maybe your example will be better? You should not get hung up only on this example of mine, I wrote exactly it, because I just don’t know about other options):
$math = new Number();
echo $math->sum(1, 2);
echo $math->sumf(1.3, 2.7);

I would like to better understand the correct architecture in OOP, I ask for help in a more relevant solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2017-01-04
@ntzch

Your example is not well thought out.
It would be more logical to assume that there is some common interface that will unite all classes and at the same time provide common functions over operands of various types.
Let's say you need to perform addition with two arguments.
For example like this:

$math = new Calculator(); // в данном случае Number плохое имя, т.к. обозначает число, а не аггрегатор вычислительных операций
echo $math->sum(1, 2); // вернет 3
echo $math->sum(1.3, 2.7); // вернет 4.0

In this case, the same method is applied to two operands of different types. Everything seems to be beautiful, but not quite. In this case, the methods are pure functions and it would be more logical to call them as static methods, like this:
echo Calculator::sum(1, 2); // вернет 3
echo Calculator::sum(1.3, 2.7); // вернет 4.0

The class implementation will look something like this
class Calculator 
{
  /**
   * Метод предназначен для суммирования двух аргументов 
   * @param number $firstArgument первый аргумент
   * @param number $secondArgument второй аргумент
   */
  public static function sum($firstArgument, $secondArgument) 
  {
    return $firstArgument + $secondArgument;
  }
}

In this case, there is no need to reinvent the wheel, because all functions for working with numbers are universal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question