In this post I will show how you can leverage PHPStan to constrain your existing classes for better type safety. This may sound abstract at first, but I do have a particular application in mind that I want to showcase.
Let me set the background for you:
I am building an ecommerce application. It has various entities like products, orders, invoices, customers, and addresses which are related to each other.
Examples:
- A customer has zero or more addresses.
- An address belongs to a single customer.
- A customer has zero or more orders.
My goal is to represent entities and relations in PHP in a type-safe manner. In particular, I want to be able to represent selectively loaded relations in the type system. For example, a type for “customer with loaded addresses but without orders” which can be statically checked with PHPStan.
Continue reading “Constrain your classes with PHPStan”