Skip to content
Home Sinan Eldem
Software

SOLID Principles

Sinan Eldem

• 4 min read

SOLID Principles

Hi everyone,

I'd like to introduce the SOLID principles, each of which I'll cover in more detail later on its own page.

Most of the content in this post is taken from Wikipedia, with extra explanations added in a Laravel context.

Single Responsibility Principle

A class (or unit of code) should have a single responsibility.

Open–Closed Principle

A class should be open for extension but closed for modification.

You can extend a class or implement an interface, but you cannot modify a class directly. This means that instead of changing a class directly, you should extend it and use that new extension.

Additionally, it means setting class properties and methods to private or protected where appropriate, so that they can't be modified by external code.

Liskov Substitution Principle

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

In PHP, this usually means creating interfaces for your code to implement. You can then swap out implementations of those interfaces (switch between them; the change here doesn't mean modifying the internals of an implementation, but replacing one implementation of an interface with another implementation of the same interface). This should be possible without having to change the application code that interacts with the implementation. The interface serves as a contract guaranteeing that certain methods will be available.

Interface Segregation Principle

Many client-specific interfaces are better than one general-purpose interface.

In general, it is preferable to create an interface and implement it many times rather than build a general-purpose class that tries to work in every situation.

Dependency Inversion Principle

Depend upon abstractions, not concrete classes.

You should define class dependencies as an interface rather than a concrete class. This lets you switch to another implementation of that interface without having to change the class that uses the dependency.

Sinan Eldem

Custom software and AI solutions with Laravel

Related posts

Software
6 min read

Laravel Eloquent Relationships Quick Reference Guide

This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.

Read more