PHP OOP Design – Correct Approach to Structure

classobject-orientedPHP

I'm converting a procedural based site to an OOP design to allow more easily manageable code in the future and so far have created the following structure:

/classes
/templates
index.php

With these classes:

ConnectDB
Games
System
User
User   -Moderator
User   -Administrator

In the index.php file I have code that detects if any $_GET values are posted to determine on which page content to build (it's early so there's only one example and no default):

function __autoload($className) {
    require "classes/".strtolower($className).".class.php";
}

$db = new Connect;
$db->connect();

$user = new User();

if(isset($_GET['gameId']))
{       
    System::buildGame($gameId);
}

This then runs the BuildGame function in the system class which looks like the following and then uses gets in the Game Class to return values, such as $game->getTitle() in the template file template/play.php:

function buildGame($gameId){

    $game = new Game($gameId);
    $game->setRatio(900, 600);

    require 'templates/play.php';
}

I also have .htaccess so that actual game page url works instead of passing the parameters to index.php

Are there any major errors of how I'm setting this up or do I have the general idea of OOP correct?

Best Answer

As far as OOP goes, there's never really a right or wrong way. There's always more roads that lead to Rome.

However, there are some caveats to avoid. Your System class looks like a God object, which is a so-called 'anti-pattern'. Best to avoid those. Also, I suspect that you're using $db and $user as global variables -- those are not encouraged in OOP. It's best to pass the DB handle to the classes that need it, either upon construction or for instance with a setDatabase() method (this is called Dependency Injection, and makes your classes easier to oversee, maintain and debug).

Finally, an autoloader might make your job as a programmer a little bit easier. This will take the job of doing the require calls out of your hands -- and also forces you to structure your code in a logical manner :)

Related Topic