Design Principles
The following design principles underpin OOP:
- Polymorphism
- Encapsulation
- Inheritance
- Abstraction
Polymorphism
Polymorphism is the ability of an object to take on many forms.
Polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs.
Polymorphism in PHP
Abstraction
The natural separation of business logic into interfaces or classes to make them easier to manage.
Increases maintainability if implemented correctly, but if implemented badly you can end up with tightly coupled code that is difficult to maintain because of the.
Goals:
High cohesion – Each class is responsible for a very limited set of business logic.
Loose coupling – Relationships between classes should be as loose as possible to make them easier to change.
Encapsulation
Objects should only reveal high-level functions for other objects to use, they shouldn’t expose all the variables and internal methods to other parts of the program. Doing so means that the object could behave in ways that the programmer may not have intended.
A real world example would be where we use “getter” and “setter” methods to set variables inside of a class where we keep the variables private. The variables cannot be modified directly in the class by external code thus maintaining the integrity of the object.
Inheritance
In object-oriented programming, inheritance enables new objects to take on the properties of existing objects.
A Class that is used as the basis for inheritance is called a Superclass or Base Class.
A Class that inherits from a Superclass is called a Subclass or Derived Class.
OOP-Specific Terminology
- Class – An encapsulation of some functionality.
- Subclass – An extension to a Base Class that inherits the Base Class functionality but adds more.
- Variable – A item of data that represents a value.
- Property – A item of data within a Class that represents a value.
- Function – Some logic that either modifies a property or returns some value.
- Method – Some logic within a Class that either modifies a property or returns some value.
- Object – Instantiation of a Class that has values in the properties declared in the Class. (The Class is the skeleton code for a live Object)
So we may have the following structure:
Animal – Class
Dog – Subclass
Otto – Object (i.e. instantiation of “Dog” Class)
Further Reading
phptherightway.com
phpthewrongway.com
medium.com/prod-io/solid-principles-takeaways-ec0825a07247
github.com/domnikl/DesignPatternsPHP
daylerees.com/php-interfaces-explained
Leave a Reply