Include-Based vs Class-Based Architecture

This is a topic I describe at length in my Organizing talk, but I would like to give the idea a home on my blog for easy reference.

Include-Based

Typical PHP uses what I call an include-based architecture. By this, I mean that the mere fact of including or requiring a file causes the execution of program code or business logic.

<?php
include 'config.php';
include 'header.php';

// ...
// do some work, probably including other files
// ...

include 'footer.php';

The application is composed of files that the user browses to directly. Those included files may include other files for additional business logic. This is the basic structure of most PHP applications.

At some point, the PHP programmer starts writing his own functions to encasulate repeated behaviors, and starts including a file of those functions. As a follow-on, the programmer may begin to adopt object-oriented programming and start to collect his functions into classes along with related data structures.

The functions and classes do not end up changing the basic structure of the include-based application. The programmer still has a series of pages that users will browse to directly. Those pages load up classes and functions and use them as helpers to perform business logic that is mostly still in the page script.

Class-Based

By contrast, a class-based architecture is what we generally see in the MVC frameworks of the past 10 years or so. The user browses to a bootstrap script (the only “page” in the whole system). That script then reads the request and picks out a business-logic class to instantiate, and calls a method on that object instance to make it run. From that point on, all behaviors are contained in class methods, not in page scripts. This is what I mean by a class-based architecture; that is, all of the main program logic is embedded in classes, not in page scripts.

In talking about the distinction between include-based and class-based architectures, one programmer I know said, “There’s no real difference between include-based and class-based. You still need to include the class file, after all.” Yes, you do need to load the class file. The difference is that no program logic is executed at loading time with a class file. Loading the class file makes it available for use, but the programmer has to instantiate it and then call methods on it for anything else to happen. With include-based architectures, merely loading the file will execute program logic.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving your codebase, all while keeping it running the whole time.