Snippets > SOLID Principles
The first five design principles of object oriented design, with examples in PHP.
Single responsibility principle: A class should have one, and only one, reason to change. An object should be made for one specific function.
Problem: The User class is for User functions, not Database functions.
class User
{
function add_user() {}
function save_user_to_database() {}
}
Solution: Separate User and Database into their own classes.
class User
{
function add_user() {}
}
class Database
{
function save_user(User $user) {}
}
Open–closed principle: A class should be open for extension, but closed for modification.
Liskov substitution principle: Derived classes must be substitutable for their base classes.
Interface segregation principle: Many client-specific interfaces are better than one general-purpose interface.
Dependency inversion principle: Depend upon abstractions. Do not depend upon concretions.