[PHP] Opzet van een dataklasse

Pagina: 1
Acties:

Onderwerpen


Acties:
  • 0 Henk 'm!

Verwijderd

Topicstarter
Hallo,

ik ben bezig met het maken van een generator voor data klasse van een mysql database.

Dit werkt tot nu toe goed. Ik zit alleen met 1 probleempje...
wanneer nu inserten of updaten.

Zoals ik het nu heb:
het nieuwe object wordt aangemaakt.
nu kunnen er 2 dingen gebeuren
1) er wordt een getRow aangeropen en er wordt een bestaande regel opgehaald uit een tabel
2) de velden worden zelf gezet.

nu heb ik een method save, die bij actie 1 een update uitvoerd en bij actie 2 een insert.
Dit werkt opzich wel, maar nu zat ik ermee, dat als ik een regel wil updaten ik altijd eerst de regel moet ophalen, ook al als ik alle nieuwe waardes heb.

Nu had ik zitten kijken naar de data klasses die llblgen genereerd, die heeft 2 losse methods voor insert en update.

Nu wilde ik vragen wat jullie "mening" hier over is? of hoe jullie het zoudne oplossen?

alvast bedankt

Acties:
  • 0 Henk 'm!

  • vinnux
  • Registratie: Maart 2001
  • Niet online
In principe heeft elke dataklasse een unieke id, hetzij enkelvoudig hetzij samengesteld. Dit vanweg de achterliggende database. Wanneer deze sleutel aan de "Constructor" wordt meegegeven wordt het object uit de database gehaald en wanneer deze sleutel niet wordt meegegeven wordt er een leeg object gemaakt.
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Class A{ 
    var $id; 
  var $insertSql = 'INSERT INTO...'; 
  var $selectSql = 'SELECT FROM...'; 
  var $updateSql = 'UPDATE ...'; 

    function A($id = null) { 
        $this->id = null; 
    if($id !== null) { 
        // Doe een select en vul de variabelen 
    $this->id = $id; 
    } 
    }

    function save(){ 
    if($this->id === null){ 
        //Doe insert 
    } else { 
        //Doe update 
    } 
    } 
}

[ Voor 61% gewijzigd door vinnux op 02-02-2004 21:03 ]


Acties:
  • 0 Henk 'm!

Verwijderd

Topicstarter
maar bij het aanmaken van een nieuw record, moet je toch ook je primarykey vullen (als het geen auto increment is).

Acties:
  • 0 Henk 'm!

  • vinnux
  • Registratie: Maart 2001
  • Niet online
Verwijderd schreef op 02 februari 2004 @ 21:43:
maar bij het aanmaken van een nieuw record, moet je toch ook je primarykey vullen (als het geen auto increment is).
Dan maak je er een en zet je die op de plaats van de id.
Het id moet een rij uniek kunnen indetificeren anders heb je niks aan een rij dat een object representeerd, aangezien anders je NOOIT de rijen uit elkaar kunt houden.
En anders voeg je in het kader van "ok ik weet wat normaliseren is, maar dit werkt beter" een auto_increment veld toe.

Of in het geval van een koppeltabel :

table A : Aid AS INT
table B : Bid AS INT
table C : Aid AS INT, Bid AS INT

A heeft als id een INT
B heeft als id een INT
C heeft als id een INT ARRAY van twee groot

Hier een voorbeeld:
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<? include_once(REL.'-inc-/classes/common/DBRowObject.class.php');
include_once(REL.'-inc-/classes/common/FormChecker.class.php');

class Genre extends DBRowObject {

    var $insertQry =
'INSERT INTO `dvd_genre` (
    `name`, 
    `description`, 
    `active`, 
    `addDate`, 
    `locked`,
    `changeDate`
) VALUES ( 
    \'$data[name]\', 
    \'$data[description]\', 
    \'$data[active]\', 
    NOW(), 
  \'$data[locked]\', 
    00000000000000
);'; 


var $updateQry =
'UPDATE 
    `dvd_genre`
SET
  `id` = `id`,
    `name` = \'$data[name]\', 
    `description` = \'$data[description]\', 
    `active` =\'$data[active]\', 
    `locked` =\'$data[locked]\', 
    `addDate` = `addDate`, 
    `changeDate` = NOW()
WHERE 
    `id` = $this->id';
    
    var $selectQry ='
SELECT
    `id`                                                    AS `id`,
    `name`                                              AS `name`, 
    `description`                               AS `description`, 
    `active`                                            AS `active` , 
    `locked`                                            AS `locked` ,
    UNIX_TIMESTAMP(`addDate`)       AS `addDate`, 
    UNIX_TIMESTAMP(`changeDate`)    AS `changeDate`
FROM
    `dvd_genre`
WHERE
    `id` = $id';


    var $name                       = '';
    var $description        = '';
    var $active                 = true;
    var $locked                 = false;
    var $addDate                = '00000000000000';
    var $changeDate         = '00000000000000';
    
    
    
    function Genre($id = null){
        $this->fieldStatus                              = Array();
        $this->fieldStatus['name']              = false;
        $this->fieldStatus['description'] = false;
        $this->idFieldName = 'id';
    $this->formChecker = new FormChecker();
        if ($id !== null){
            $this->fromDatabase($id);
        }
    }
    
    function isLocked(){
     return $this->locked;
    }
    
    
    function setLocked($locked){
        if ($locked === true){
            $this->locked = true;
        } else {
            $this->locked = false;
        }
    }
    
    function isActive(){
     return $this->active;
    }
    
        function setActive($active){
        if ($active === true){
            $this->active = true;
        } else {
            $this->active = false;
        }
    }
            
    function setName($name){
        $ok = false;
        if( $this->formChecker->isValidFormValue($name,'STRING',1,50) === true ){
            $name = trim($name);        
            $qry='SELECT COUNT(*) FROM `dvd_genre` WHERE name=\''.$name.'\'';
            if(isset($this->id))
             $qry .= ' AND `id` <> '.$this->id;
            
            $res = qry($qry);
            if(mysql_result ( $res, 0 , 0) == 0){
                $this->name=$name;
                $ok = true;
                $this->fieldStatus['name'] = TRUE;
            }
        }
        return $ok;
    }

    function delete(){
        $deleted = false;
        $qry='SELECT COUNT(*) FROM `dvd_dvd` WHERE genre_id0='.$this->id.' OR genre_id1 ='.$this->id.' OR genre_id2 ='.$this->id;
        $res = qry($qry);
        if( mysql_result ( $res, 0 , 0) == 0) {
            $qry = 'DELETE FROM dvd_genre WHERE id='.$this->id;
            qry($qry);
            $deleted = true;
        }
        return $deleted;
    }
    
        
    function setDescription($description){
        $ok = false;
        if( $this->formChecker->isValidFormValue($description,'STRING',1) === true){
            $this->description = trim($description);        
            $this->fieldStatus['description'] = TRUE;
            $ok = true;
        }
        return $ok;
    }   

    function getName(){
        return $this->name;
    }
    
    function getDescription(){
        return $this->description;
    }
    
    function getAddDate(){
        return $this->addDate;
    }
    
    function getChangeDate(){
        return $this->changeDate;
    }
    
}
?>
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<?

//include_once(REL.'include/classes/user/FormChecker.class.php');
/**
 Author     :   Vincent Gouw
 Created    :   05-05-2002
 ToDo       :   - Rollback
 [Changes]
 21-07-2002
 Added comments and adapted the class to the given Object Model.
 15-10-2002
 Added object var fore FormCheker object
[DESCRIPTION]
This object is an Abstract reprenstation of an unique item in a database.
This item can be manipulated. The object itself is responsible for it's own data and 
the representation in the database.
**/
class DBRowObject{
   /**
    * [private boolean] 
    * Indicates if the data of the object should be retrieved afther the 
    * functions toDatabase() or delete() ar called. When the flag is true the 
    * function fromdatabase() is called to retrieve the data from the database.
    **/
    var $reInit = FALSE;    
   /**
    * [private String]
    * The unique representations value of this object in the database
    * This can be one value or an array of values, depending on the number of field which form this
    * id. The var idFieldName contains these values.
    */
    var $id;
   /**
    * [private String]
    * The field name(s) which represent a unique item in the database.
    * It can be one value or an array of values;
    */
    var $idFieldName;
   /**
    * [private String]
    * Contains the last group of array messages;
    */
    var $errorMsg = Array();
   /**
    * [private String]
    * The Query(ies) which is responsible for putting this object into the database
    */
    var $insertQry;
    /**
    * [private String]
    * The Query(ies) which is responsible for updating this object into the database
    */
    var $updateQry;
    /**
    * [private String]
    * The Query(ies) which is responsible for updating this object into the database
    */
    var $deleteQry;
   /**
    * [private String]
    * The Query(ies) which is responsible for selecting this object from the database
    */
    var $selectQry;
   /**
    * [private String]
    * This array indicates if the different fields are correctly filled.
    * When the are correctly filled the object can be written to the database.
    */
    var $fieldStatus = Array();
    
    
    
    var $formChecker;
    
    

    
    function getErrorMsg(){
        return $this->errorMsg;
    }
    
    function isDatabaseReady(){
        $isDatabaseReady = TRUE;
        $nr = 0;
        foreach($this->fieldStatus as $key => $value){
            if ($value !== TRUE){
                $isDatabaseReady = FALSE;
                break;
            }
        }
        return $isDatabaseReady;
    }
    
    function DBRowObject($id){
        $this->fromDatabase($id);
    }
        
    function getId(){
        return $this->id;
    }
        
    function fromDatabase($id){
        $ok = FALSE;
        // If id is an array and idFieldName is an array and the have exactly the same number of fields,
        // then we can set the vars and retrieve the row from the database 
        if(is_Array($id) && is_Array($this->idFieldName) && count($id) === count($this->idFieldName)){
            for($nr = 0 ; $nr < count($this->idFieldName) ; $nr++){
                //Declaring vars at runtime !
                $tmp = $this->idFieldName[$nr];
                $$tmp = $id[$nr];
            }
        } else if(!is_Array($id) && !is_Array($this->idFieldName)){
            //Declaring var at runtime !
            //echo($this->idFieldName.'='.$id);
            $tmp = $this->idFieldName;
            $$tmp = $id;
        } else {
         // Well we can't do a thing can we !
         echo('[DBRowObject] fromDatabase($id = '.$id.') NBO fields between $id and $this->fieldName is not the same.');
         return $ok;
        }
        
        eval ("\$qry = \"$this->selectQry\";");
        $res = qry($qry);
        if (mysql_num_rows($res) == 1){ 
            $ok = TRUE;
            $row = mysql_fetch_array($res);
            foreach ($row as $key => $value){
                if (!preg_match("/^[0-9]{1,}$/",$key)){
                  if ($value == null)
                     $this->$key = null;
                    else if ($value == 'true')
                      $this->$key = true;
                    else if ($value == 'false')
                      $this->$key = false;
                    else
                    $this->$key =  stripslashes($value);
            
                }
            }
            foreach ($this->fieldStatus as $key => $value){
                    $this->fieldStatus[$key] = true;
            }
            
        } 
        return $ok;
    }
    
    function toDatabase(){
        $this->preDatabase();
        $this->error='';
        $ok     = TRUE;
        if(!$this->isDatabaseReady()){
            $ok = FALSE;
            $this->error='Object is not database ready';
            echo('Object is not database ready');
        }
        else {
            //// Well ok you can manipulate something
                // Get all declared vars
            $data = get_object_vars($this);
            // Addslashes to the vars to do go into the database, let's check.
            foreach ($data  as $varname => $value) {
            if (     $varname === 'reInit'          || $varname === 'id' 
                        || $varname === 'dbConnection' || $varname === 'error' 
                        || $varname === 'insertQry'         || $varname === 'updateQry' 
                        || $varname === 'selectQry'         || $varname === 'nboOk' 
                        || $varname === 'nboToBeOk' ) {
                        ;
                } else {
                  if ($data[$varname] === null){
                     $data[$varname] = '<-{}=[NULL]={}->';
                 } else if ($data[$varname] === true)
                      $data[$varname] = 'true';
                    else if ($data[$varname] === false)
                      $data[$varname] = 'false';
                    else
                    $data[$varname] = @addslashes($data[$varname]);
                }
        }
                    
            // Let's look if it is a update or a insert
            if (isset($this->id)){
                eval ("\$qry = \"$this->updateQry\";");
                $qry =  str_replace('\'<-{}=[NULL]={}->\'','NULL',$qry);
            //echo('toDatabase : UPDATE QRY :'.$qry);
                qry($qry);
            } else {
                eval ("\$qry = \"$this->insertQry\";");
                $qry =  str_replace('\'<-{}=[NULL]={}->\'','NULL',$qry);
            //  echo('toDatabase : INSERT QRY :'.$qry);
                qry($qry);
                $this->id=mysql_insert_id(); 
            }
            // Shall we reInit al the vars ?
            if ($this->reInit === TRUE){
                $this->fromDatabase($id);
            }
        }
        $this->postDatabase();
        return $ok;
    }
    
    /**
     * Sets the reInit value to TRUE or FALSE
     * When the reInit value is TRUE the object will be rebuild afther a succesfull call of toDatabase
     */
    function setReInit($reInit){
        if ($reInit === TRUE){
            $this->reInit=TRUE;
        } else {
            $this->reInit=FALSE;
        }
    }
    
    function getReInit(){
        return $this->reInit;
    }
    
    function getError(){
        return $this->error;
    }
    
    function preDatabase(){
    }
    
    function postDatabase(){
    
    }
    
}
?>

[ Voor 111% gewijzigd door vinnux op 02-02-2004 21:52 ]