Creating a Shopping Cart Class Using Object-Oriented Programming in PHP
One of the many benefits of object-oriented programming (OOP) is reusability: A well-defined class can easily be applied to different projects, even by different developers. And thanks to some of the more recent additions to PHP, such as interfaces and the Standard PHP Library (SPL), top-quality classes can be created with a wealth of flexibility and power.
The heart of a shopping cart can be represented in just two classes: a cart class and an item class. Item objects are added to an array stored within the cart object. With this approach, on each specific e-commerce project you only need to customize the item class: The cart itself is entirely reusable.
The Cart Class’s Needs
OOP always begins with design, not code, which in turn starts with the identification of needs. At the bare minimum, the cart must store the items that have been put in the cart. The items should be updatable (e.g., to change the quantity of an item in the cart) and removable. And, of course, those items need to be fetchable as wellfor example, to display the cart’s contents. Mostly, though, the cart should be kept rather generic to make it more universally usable. If done correctly, the customization would go in the item class definitions that are specific to each site.
With this in mind, let’s first create the basic cart functionality: adding, updating, and deleting items. Then let’s modify the class so that it can be used in loops to access the cart’s contents. After that, I’ll define a barebones item class and walk through the code usage.