Today I take my first steps down a path that really scares me — object oriented PHP. I love object oriented design, and I feel like I understand it pretty darn well. The question is how to take a very procedural PHP application and graft some object oriented bits onto it. This application happens to run on PHP4, so I’ll be investigating from that perspective. The first stop is Chapter 18 in the PHP manual.
What I’m working on is a set of improvements to a reporting application. Right now the report is a fairly standard PHP page. It takes some parameters on the URL, turns them into a SQL statement, and then displays the results of that SQL statement on the page. Naturally, feature requests have come in and now the report is becoming more and more complex. Some columns that can appear on the report should only be displayed for users with a certain access level. Users want to be able to customize the report to show only certain columns, and to show those columns in a particular order. There are also a number of filtering options for the report.
The number one feature that requires a new approach in creating the report is the request to enable users to choose the order in which the columns will be displayed. When the column order is fixed, you can just list the columns on the page and wrap them in
if statements that control whether or not the column is displayed. When the order is customized, you have to write some kind of control structure that presents the columns in the order that the user chooses.
When I got to that point, I realized that it may make sense to create a class named
Column. The members of the class are the label for the column, its name in the database, the level of access required to view it, whether or not the report can be sorted on this column, and the SQL to include in the select clause for this column. Each column that can potentially appear on the report can be stored as a static object, and a user’s preferences are simply an ordered collection of
Column objects. To display the report, you just iterate over that collection once for each row in the report (plus once for the header).
This is pretty rudimentary object oriented design. The results of the query are still handled in a completely procedural manner, as is just about everything else. All it does is encapsulate some characteristics of one component of the report. In fact, what it really seems like I’m doing is creating a fancy hashtable. Baby steps at first, I suppose.