CodeIgniter Forums
Schedule algorithm - Printable Version

+- CodeIgniter Forums (
+-- Forum: Archived Discussions (
+--- Forum: Archived Development & Programming (
+--- Thread: Schedule algorithm (/showthread.php?tid=20009)

Schedule algorithm - El Forum - 06-25-2009


I'm working on a schedule algorithm for a hockeyleague and I'm almost done, but there is something that bugs me and keeps me awake at nights!

In my code I use require once 'blah.php'; to create different instances of a class called Schedule_team like this:
Quote:$arr = array();
foreach($team_array as $ta)
$arr[] = new Schedule_team($ta['name'])

$team_array is an array with some information about every team.

Schedule_team holds information about how many times a team has met the others.

I wonder if there is any smart way to get around this "require once" and "new Scheldule_team();" problem of mine.

Schedule algorithm - El Forum - 06-25-2009

[eluser]Pascal Kriete[/eluser]
How about a factory?
class Schedule_team
    // Stores objects
    private static $_teams = array();
    // Regular class variables
    public $name;
    // Constructor - factory does most of the work
    public function __construct() {}
    // Factory
    public static function factory($name)
        if ( ! isset(Schedule_team::$_teams[$name]))
            $team = new Schedule_team();
            $team->name = $name;

            Schedule_team::$_teams[$name] = $team;
            $team = Schedule_team::$_teams[$name];
        return $team;

Make that a library, and use it:

$a = Schedule_team::factory('ateam');
$b = Schedule_team::factory('bteam');

echo $a->name, ' ', $b->name;

In it's current form it will also return a team if you already have on of the same name. Depending on how complex this class is you may want to separate the factory from the actual schedule_team class.