Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Creating a Shopping Cart Class Using Object-Oriented Programming in PHP

  • Print
  • + Share This
E-commerce is clearly one of the most prominent uses of PHP today, a trend that’s certain to continue. An e-commerce site can be created in many ways, whether that means using a third-party application like osCommerce or writing one from scratch in classic, procedural PHP code. In this article, web developer Larry Ullman presents the class structure you could use to create the core of a shopping cart application using object-oriented programming.
Like this article? We recommend

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 well—for 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.

  • + Share This
  • 🔖 Save To Your Account