PHP instanceof Operator Tips

26th January 2021 - 8 minutes read time

The instanceof operator in PHP is great at making sure you are looking at a type of object before acting on it. Whilst it's straightforward to use on its own, using it can lead to some undesirable side effects.

As a basic example, let's create a couple of interfaces and classes to show the instanceof operator in action. Rather than just have some test names I am using object names that you might find in a system. This consists of User and Order that might form part of a commerce system.

Using PDO To Create A Data Access Object

4th August 2020 - 12 minutes read time

A Data Access Object (DAO) is a way of taking data out of a database or API and present it in a unified way across your application. As a design pattern this has uses in standardising how a particular bit of data is passed around, without having to resort to using arrays to accomplish the same job.

I was doing some work with PHP's PDO library the other day when I noticed that I could fetch data out of a database using the fetchAll() method with the PDO::FETCH_CLASS flag. This flag automatically returns the data in an object. This got me thinking more about how this worked, but I couldn't find many articles talking about this. Hence this post.

Setting Things Up

Let's take a class called SpecialText that will store an ID and some text, along with a __toString() method to allow the printing of those values. We will use this class throughout this post to store data from the database.

Traits Versus Inheritance In PHP

9th February 2020 - 6 minutes read time

The other day I was conducting a code review and found that a developer had used a trait to give two classes the same group of utility methods. Whilst there was nothing wrong with this in terms of functionality, I asked the developer why they had chosen to use traits instead of inheritance. We eventually decided that an inheritance model would be better suited to the situation but I thought I would go through some of the thought processes here.

What Is A Trait?

A trait, if you weren't aware, is like a class, but you don't instantiate it directly. Traits are defined using the trait keyword and are otherwise quite like a class in structure.

The idea is that code is essentially copied into the class you want to use it in from the trait and the class acts like it had that code all along. For example, let's take a simple trait.

SOLID Principles In PHP

20th August 2018 - 14 minutes read time
SOLID is a set of object oriented design principles aimed at making code more maintainable and flexible. They were coined by Robert "Uncle Bob" Martin in the year 2000 in his paper Design Principles and Design Patterns. The SOLID principles apply to any object oriented language, but I'm going to concentrate on what they mean in a PHP application in this post.