phparchitect-2019-08

(Rick Simeone) #1
30 \ August 2019 \ http://www.phparch.com

Education Station
Writing DRY, SOLID FOSS OOP CRUD Code

Open/Closed Principle
The Open/Closed Principle originates from the 1988 book
Object-Oriented Software Construction by Bertrand Meyer.
He defined it as follows:



  • A module will be said to be open if it is still available for
    extension. For example, it should be possible to add fields
    to the data structures it contains, or new elements to the
    set of functions it performs.

  • A module will be said to be closed if [it] is available for
    use by other modules. This assumes that the module has
    been given a well-defined, stable description (the inter-
    face in the sense of information hiding).In more modern
    terms, this means using object models that allow abstract
    classes and interfaces to help make the code more
    extensible via inheritance and composition. Objects are
    generally considered “open” because we can extend them
    without needing to modify the original parent code, but
    closed in that it defines a stable API.
    The idea of code visibility comes into play here for many
    developers. Do we make something public, protected, or
    private? Should this class be considered final? The decisions
    we make with our classes directly impact this idea of open/
    closed.


Liskov Substitution Principle
The Liskov Substitution Principle is generally what causes
the debate between inheritance versus composition. This
principle states that objects should be replaceable with chil-
dren without affecting the ability of the program to run.
For example, in the classic example of animals, our program
should not care if we pass in a Dog object or a Cat object, as
long as all we care about is that we are working with an Animal
object. As soon as we start to care about sub-types that are
being passed and changing behavior, we break this principle.

Listing 4


  1. function printLegs(Animal $animal) {

  2. $message = "This animal has %d legs";

  3. if ($animal instanceof Fish) {

  4. $message = "This fish has %d fins";

  5. }

  6. print sprintf($message, $animal->getNumLegs());

  7. }



  8. $fish = new Fish();

  9. $fish->legs = 5;

  10. printLegs($fish);

Free download pdf