loading...

Simple Calculator in PHP (OOP principles)

naveenkolambage profile image Naveen Dinushka ・2 min read

So lets build a calculator which does the following.
1) Addition
2) Multiplication
3) Division
4) Subtraction

The folder and file structure is given below

Alt Text

Lets get the html index.php sorted first, so whats in it?

<?php

 include 'includes/class-autoload.inc.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<form action="includes/calc.inc.php" method = "post">

    <p>Calculator V01</p>
    <input type= "number" name="num1" placeholder="First number">
    <select name="oper" >
      <option value="add"> Addition </option>
      <option value="sub"> Substraction </option>
      <option value="div">Division </option>
      <option value="mul">Multiplication </option>
    </select>
    <input type="number" name="num2" placeholder="Second number">
    <button type="submit" name="submit">  Calculate</button>

</form>

</body>
</html>

The code above should be self-explanatory, if you are unsure about the class-autoload.php file have a look at this article(
https://dev.to/naveenkolambage/autoload-classes-in-php-4474 ) about it.

And here is the code we have in class-autoload.inc.php

<?php

spl_autoload_register('myAutoLoader');

function myAutoLoader($className){
    $url= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

    if(strpos($url, 'includes')!==false){
        $path = '../classes/';
    }
    else{
        $path = 'classes/';
    }
    $extension = '.class.php';
    require_once $path.$className.$extension;
}

Then we look at the calculator class file which is calc.class.php

<?php

class Calc{
    public $operator;
    public $num1;
    public $num2;


    public function __construct(string $one, int $two, int $three){
        $this->operator = $one;
        $this->num1 = $two;
        $this->num2 = $three;
    }


    public function calculator(){
     switch ($this->operator) {
         case 'add':
            $result = $this->num1 + $this->num2;
            return $result;             
            break;
        case 'sub':
            $result = $this->num1 - $this->num2;
            return $result;             
            break;
        case 'div':    
             $result = $this->num1 / $this->num2;
             return $result;             
             break;
        case 'mul':    
             $result = $this->num1 * $this->num2;
             return $result;             
             break;

     }
    }

}

Then the next file is calc.inc.php

<?php
include 'class-autoload.inc.php';

$oper = $_POST["oper"];
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];

$calc = new Calc($oper,$num1,$num2);

try {
    echo $calc->calculator();
} catch (TypeError $e) {
    echo "Error!: " .$e->getMessage();
}

?>

When we load this up on xampp we can see the following.

Alt Text

I have created a small video on this https://youtu.be/lU23DLYte6w

Discussion

markdown guide
 

Fine but let's me add a bit of code

<?php
class Calc{
    public $num1;
    public $num2;
    public function __construct(int $two, int $three){
        $this->num1 = $two;
        $this->num2 = $three;
    }
}


class CalcService{
    // public $operator; // it is not required, this value has a short life.
    public static function calculator($operator,$calc){
     switch ($operator) {
         case 'add':
            $result = $calc->num1 + $calc->num2;
            return $result;             
            break;
        case 'sub':
            $result = $calc->num1 - $calc->num2;
            return $result;             
            break;
        case 'div':    
             $result = $calc->num1 / $calc->num2;
             return $result;             
             break;
        case 'mul':    
             $result = $calc->num1 * $calc->num2;
             return $result;             
             break;

     }
    }
}

Your original class usually is called the Business Object Class. It's a class that groups the fields and the logic (methods). While it works in the short run but it tends to fail in the long run (biggest projects).

So, our calc.inc.php could be written as follow

<?php
include 'class-autoload.inc.php';

$oper = $_POST["oper"];
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];

$calc = new Calc($num1,$num2);

try {
    echo CalculatorService($oper,$calc);
} catch (TypeError $e) {
    echo "Error!: " .$e->getMessage();
}

?>

Why the change?

Let's say our code uses the database. So, if we have a class for the data and another class for the methods, then we could add a third service class for all methods that involve the database, for example, CalculatorRepo, CalculatorDao or CalculatorDAL.

i.e. we are doing SRP.

It is nothing special. For example, a Webservice is exactly a service class but shared via web. Our first class (Calc) usually is called the MODEL.

Even more, we could do a method that fetches ($_POST) the values from the post and creates the model Calc (if the information is right).