Using PHP Objects to Access Your Database Tables (Part 1)
By Tony Marston2005-04-05
Intended Audience
This tutorial is intended for developers who have already written code to get data in and out of a MySQL database, but who wish to discover if there are any benefits of adopting an Object Oriented approach. This tutorial will show you how to create an abstract class which can communicate with any database table, and then how to create subclasses containing the implementation details for each individual table within your application. The end result is that you never have to code any of the SQL SELECT, INSERT, UPDATE or DELETE statements for any table as they will be generated at runtime.
As this object will be responsible for carrying out all data access it is sometimes referred to as a Data Access Object (DAO).
There are quite a few so-called OOP 'experts' who seem to think that having a separate class for each table in the database is a silly idea, so let me explain the logic in my approach. If I am designing an application to deal with such real-world entities as 'customer', 'product' and 'invoice' then I will want a software module/component/object to deal with each of these entities. This software module will contain (encapsulate) all the information required to process the entity, such as the business rules, and will also be required to read from and write to the database table. In my previous language the word 'entity' was synonymous with the word 'table', so when I talk about creating a class for a database table I actually mean a class for an entity. This includes, but is not limited to, the ability to communicate with the database table associated with that entity. So, entity=table and entity=class, therefore class=table. Simple.
I have to admit up front that I do not come from an OOP (Object Oriented Programming) background. In fact PHP is the first language I have used that has had OOP capabilities. Now there are some people who argue that PHP is not a 'proper' OO language, but they are just nit-picking. While it is true that PHP was not originally designed as an OOP language, and that some more advanced features will not be available until PHP 5 is released, I have found the capabilities of PHP 4 more than adequate for my purposes.
In this tutorial you will learn the following:
• How to define a class with properties and methods.
• How to create an object (an instance of) a class.
• How to create a class which extends another class.
• How to communicate with an object from within a PHP script.
Tutorial Pages:
» Intended Audience
» Prerequisites
» An introduction to OO functionality within PHP
» My 'database_table' class
» Using this Class
» Standard functions
» Summary
