azz0r

"Put it where? You naughty boy"

Posts: 30,671

Reputation:

17th Aug 08, 12:12pm | Quote | Blogs | Profile | RSS Feed
Right so when I create a table I then have to create a class that saves, creates, deletes and loads rows for it...which isn't a difficult task but its timely for something thats essentially a rename job with tweaks.

WELL, I decided to challenge myself and create a class that automatically get the tables fields and then manages the methods for me.

Someone on google might find this highly useful

<?php
/*<
    $object = new Mimic('Post');<
    $object->Delete(1); //without the row called<
    $object->Save();<
    $row = $object->LoadByField('id', 100004);<
    $row = $object->Create(array(NULL, 'whut whut', 1, 2, '81.101.88', '_TIME', '_TIME'));    <
    $row->Delete(); //with the row called<
    $objects = $object->LoadAll(0, 15);<
*/



class 
Mimic {


    public 
$classTable;
    public 
$classFields = array();


    function 
__construct($classTable) {

        
$db        Database::GetInstance();
        
$query     $db->query("SHOW COLUMNS FROM $classTable ");

            while (
$row $query->fetch_object()) {
                
$this->classFields[] = $row->Field;
            }

        
$this->classTable $classTable;

    }


    public function 
LoadByField($field$variable) {

        try {
            
$db Database::GetInstance();
            
$result $db->query("SELECT * FROM ".$this->classTable." WHERE `$field` = '$variable' ");

                if(
$result && $result->num_rows 0) {
                    return 
self::LoadByArray($result->fetch_object());
                } else {
                    throw new 
ApplicationException("Could not load table: ".$this->classTable."; field: $field; variable: $variable");
                }

        } catch(
DatabaseException $e) {
            throw new 
ApplicationException($e->getMessage(), $e->getCode());
        }
    }


    public function 
LoadByArray($results) {

        try {
            foreach(
$results as $key => $value) {
                
$this->$key $value;
            }

            return 
$this;

        } catch(
DatabaseException $e) {
            throw new 
ApplicationException($e->getMessage(), $e->getCode());
        }
    }


    public function 
LoadAll($from=NULL$to=NULL$fields=NULL$where=NULL$order=NULL$count=0) {

        try {
            
$db Database::GetInstance();
            
$from    = ($from == NULL)     ? 0     $from;
            
$to        = ($to == NULL)     ? 0     $to;
            
$fields = ($fields == NULL) ? '*'     $fields;
            
$where     = ($where == NULL)     ? NULL     "WHERE $where";
            
$order     = ($order == NULL)     ? NULL     "ORDER BY $order";

            if(
$count == 1) {
                
$query $db->query("SELECT 1 FROM ".$this->classTable." $where") or die($db->error);
                return 
$query->num_rows;
            }

            
$query $db->query("SELECT $fields FROM ".$this->classTable." $where $order LIMIT $from, $to") or die($db->error);

                if(
$query && $query->num_rows 0) {
                    
$results = array();
                        while(
$q $query->fetch_object()) {
                            
$object     = new self($this->classTable);
                            
$results[]     = $object->LoadByArray($q);
                        }
                    return 
$results;
                }
            return 
false;

        } catch(
DatabaseException $e) {
            throw new 
ApplicationException($e->getMessage(), $e->getCode());
        }
    }


    public function 
Save() {

        try {
            
$db     Database::GetInstance();
            
$string NULL;

            foreach(
$this->classFields as $field) {
                
$string .= "`$field` = ".$db->safe($this->$field).", ";
            }

            
$result $db->query("UPDATE ".$this->classTable." SET ".substr($string0, -2)." WHERE `id` = ".$this->id);

                if(!
$result) {
                    return 
false;
                } else if (
$db->affected_rows >= 0) {
                    return 
true;
                } else {
                    return 
false;
                }

        } catch(
DatabaseException $e) {
            throw new 
ApplicationException($e->getMessage(), $e->getCode());
        }        
    }


    public function 
Create($values=array()) {

        try {
            
$db         Database::GetInstance();
            
$theFields NULL;
            
$theValues NULL;

            if (
count($values) != count($this->classFields)) {
                throw new 
ApplicationException('The value count differs from the class field count.');
            }

                foreach(
$this->classFields as $field) {
                    
$theFields .= "`$field`, ";
                }

                foreach(
$values as $value) {

                    if (
is_null($value)) {
                        
$theValues .= "NULL, ";
                    } else if (
$value == '_TIME') {
                        
$theValues .= "".time().", ";
                    } else {
                        
$theValues .= "".$db->safe($value).", ";
                    }
                }

                
$db->query("INSERT INTO ".$this->classTable." (".substr($theFields0, -2).") VALUES (".substr($theValues0, -2).") ") or die($db->error);

                    if(
$db->affected_rows 0) {
                        return 
$this->LoadByField('id'$db->insert_id);
                    } else { 
                        return 
false;
                    }

        } catch(
DatabaseException $e) {
            throw new 
ApplicationException($e->getMessage(), $e->getCode());
        }        
    }


    public function 
Delete($id=0) {

        try {
            
$db Database::GetInstance();

            if (
$id 0) {
                return 
$db->query("DELETE FROM ".$this->classTable." WHERE `id` = $id ");
            } else if ( empty(
$this->id {
                throw new 
ApplicationException('You must select a row before trying to delete.');
            } else { 
                return 
$db->query("DELETE FROM ".$this->classTable." WHERE `id` = ".$this->id);
            }

        } catch(
DatabaseException $e) {
            throw new 
ApplicationException($e->getMessage(), $e->getCode());
        }        
    }


}


?>


Jacks gotta have something to say on this?

Jack

"I'm flying like a rocket-ship."

Posts: 13,242

Reputation:

17th Aug 08, 4:38pm | Quote | Blogs | Profile | RSS Feed
I have actually. Looking at that and then looking back over source that you sent me a year or so ago, your coding has come on in leaps and bounds!

azz0r

"Put it where? You naughty boy"

Posts: 30,671

Reputation:

17th Aug 08, 6:47pm | Quote | Blogs | Profile | RSS Feed
Merci

Working on a sunday night, how exciting.

chis

"Stix"

Posts: 2,082

Reputation:

17th Aug 08, 6:57pm | Quote | Blogs | Profile | RSS Feed
I wish i never stopped doing PHP
caek

azz0r

"Put it where? You naughty boy"

Posts: 30,671

Reputation:

17th Aug 08, 7:19pm | Quote | Blogs | Profile | RSS Feed
I've just decided with the deadline so close I'm going to have to assign someone else to work on the competition part of the new site, bearing in mind it has to be totally dynamic, its a nightmare.

So I've started making a doc with information for the users to follow...the more I write the more difficult it seems its going to be!

<?php

/*<
VITAL INFORMATION<
<
Tables:<
Competition<
General information.<
<
Prize<
the following fields on this table are used to select how many of what and what database table it refers to:  `has_count` ,`has_type` ,`has_table` ,<
<
Competition_Prize<
competition_id + prize_id. One prize could be used on another competition, so prizes are linked to competition via this. The place field refers to what place this prize is about.<
<
Competition_Winner<
competition_prize_id + user_id. From this you can select the prize details and the competion details aswell as who it was who won!<
*/


switch(
$action):


case 
'latest_competitions' :
break;

case 
'view_competition' :

    
$competition Competition::LoadByField('id'$id);

    if(
$competition->expires time()) {
        
//competition details<
    
} else {
        
Competition_Winner::LoadByCompetitionId($id);
        
//SELECT * FROM Competition_Winner cw JOIN Competition_Prize<
    
}

break;


case 
'latest_winners' :
break;



endswitch;


?>