Program to an interface 🎭

Published Sep 16 2023

inheritence
interfaces
php
OOP

Programming to an interface is one of the most important principles of reusable object-oriented design. While it still falls under the inheritence paradigm, it is brings a unique approach in that it promotes flexibility and decoupling. Here's why:

programming to an interface (in PHP) involves designing your code to interact with objects through their interfaces rather than their specific implementations. This then makes it easier to swap out different implementations of a given interface. For example, given the following code:

interface Athlete {
    public function getAthleticism();
}

class Cyclist implements Athlete {
    private $ageScore;
    private $ageWeight;
    private $staminaScore;
    private $staminaWeight;
    private $effortScore;
    private $effortWeight;

    public function __construct(
        $ageScore, 
        $ageWeight, 
        $staminaScore,
        $staminaWeight,
        $effortScore,
        $effortWeight,
    ) {
        $this->ageScore = $ageScore;
        $this->ageWeight = $ageWeight;
        $this->staminaScore = $staminaScore;
        $this->staminaWeight = $staminaWeight;
        $this->effortScore = $effortScore;
        $this->effortWeight = $effortWeight;
    }

    public function getAthleticism() {
        return ($this->ageScore * $this->ageWeight) + ($this->staminaScore * $this->staminaWeight) + ($this->effortScore * $this->effortWeight);
    }
}

function calculateAthleticism(Athlete $athlete) {
    echo "The player athleticism is: " . $athlete->getAthleticism() . "\n";
}

calculateAthleticism(new Cyclist(7, 0.4, 8, 0.3, 9, 0.3));

In the above example, we only have to make sure that all our athletes impliments the interface Athlete. That way we can expect any athlete object instantiated from the any concrete class that impliments the Athlete abstract class to have the method getAthleticism().

Now, we don't have to worry about the granularity of the implimentation. Only that it adheres to the rules of the abstract.

© 2025 Elvis Magagula, All rights reserved