You may be wondering who Nex is. Well it’s m notebook, a Dell Latitude D600 I bought about 3 years ago, when starting my studies at ETH Zurich. It’s dead…
It all started a week ago when all the sudden the disk started to spins uncontrollably (much higher than the 5′400 RPM it’s supposed to do), so I shut it off with a hard reset, when booting again it complained that it couldn’t find the primary disk, so I let it turned off for a while, and miracle, it started again. It scared me so much that I decided to start making backups, and not a day to soon. I set up a simple rsync script that would sync my homefolder to another box, so I could at least go back if all went snafu.
Today it did. After some clicking noises, the notebook started not reacting properly and I decided to shut it down… it never came up again…
Well, hopefully I can get hold on a disk soon because it’s my main working machine. Until then: Rest in Peace Nex
A while back I’ve been working on some PHP Projects that required me to create an abstraction layer for my objects. It should be easy to use it and it should be very short as I wanted to concentrate on the real program and not the repetitive work, which persistence still is with PHP. So I wrote my own little Database wrapper with basic functionality making it as lightweight as possible. The next step was modelling a BaseVO (Base Virtual Object) that the other would inherit from. This meant implementing a way to retrieve both many-to-one and one-to-many relations. So let’s get started with the code:
BaseVO.class.php
First of all let’s define the common variables that we will need in each and every class:
The $table will tell us what table the instances of this type will be saved in, the $className will tell us what type of class we are working on (more on this later) and the $id should be pretty obvious While $id can be left as is in this class, $className and $table will have to be set in every descending class.
Next we need a way to retrieve the object from the database:
/**
* Loads an entry given it's id.
*/function load($id){global$db;
$this->loadFromArray($db->queryArray("SELECT * FROM ".$this->table." WHERE id='".$id."';"));
}/**
* Loads the object from an array, possibly from an SQL-ResultSet.
*/function loadFromArray($arr){if(count($arr)<2)return;
foreach($arras$k =>; $v){$this->$k = $v;
}}
As you can see all the magic is in loadFromArray which assigns every value from the resultset to the corresponding variable in the object. load is simply there to make it easy to load the object without a preexisting resultset. Why did I choose to do it this way? Because, as you’ll see later, I will often have ResultSets of more than one row that have to be transformed into an object, and executing a query for each and every one of them is not practical. The idea is just to get a whole bunch of rows and then map them to objects. SQL is our friend remember?
Now that we can load the objects from the database, what would be more obvious than trying to save them back to the Database? Here you go:
function save(){global$db;
// Get the fields.$rs =& mysql_query("DESCRIBE ".$this->table.";");
while($t = mysql_fetch_assoc($rs)){$fields[$t["Field"]] = $this->$t["Field"];
}$db->saveArray($this->table,$fields);
}
Uhm, not much to see here, sorry. To understand this we’ll have to come back later when discussing the Database-Wrapper. For now just remember that all this does is filter out all the object variables that are not in the corresponding table, as MySQL will return an error when trying to set a variable that is not also in the table. Notice that this seems to be working only with MySQL, since most others don’t understand the DESCRIBE query
Anyway let’s move on to relations. First there is the many-to-one relation which means that the table has a foreign key pointing to another table. This is quite easy to implement, but I decided to give it an extra feature: caching. Let’s see how it’s done:
This may look a bit tricky but it isn’t. getForeign take a $className that will be used to create the instance of the object we are trying to get, if it has not yet been cached, and it gets a $key, this is mainly the name of the variable inside the current object. It then construct the $cacheName which will be used to access the cached version inside this object and if the object has not yet been cached it retrieves it from the database, using the load function described above. setForeign works in a similar fashion, but unsets the cache if the passed value is an id and not an instance of the object.
Ok, we’re almoset done with the BaseVO, last thing we have to look at is getMany which represents the one-to-many relation:
function &getMany($className,$options){global$db;
$data =& $db->queryAllArray("SELECT * FROM ".(empty($options['table'])?$className."s":$options['table'])." WHERE ".(empty($options['foreign'])?$this->className:$options['foreign'])."='".$this->id."';");
$res = array();
foreach($dataas$d){$o =& new$className();
$o->loadFromArray($d);
$res[]=& $o;
}return$res;
}
This code is pretty straightforward as it just gets a bunch of rows that have the foreign key set to the current objects id (the usual way to do this in relational mapping), and then creates object instances from them. The new thing is that now we have an options argument which is supposed to be an array containing optional variables such as table and foreign that will tell us which table to use and what column in that is to use as foreign key. That’s about it for the BaseVO class, later I’ll show an example on how to use it.
Database.class.php
As this is simply a wrapper to the mysql-functions I’ll just post it here and comment only the saveArray function.
< ?php
/**
* BaseVO, Basic Virtual Object, abstraction for object persistence.
* Copyright (C) 2007 Christian Decker
*
* @author Christian Decker <decker.christian@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http ://www.gnu.org/licenses/>.
*/class Database {var$fd = null;
function Database($host, $username, $password, $dbname){$this->fd =& mysql_pconnect($host, $username, $password) or die(mysql_error());
mysql_select_db($dbname,$this->fd) or die(mysql_error());
}function close(){returnmysql_close($this->fd);
}function &query($sql){print($sql."\n");
$rs =& mysql_query($sql) or die(mysql_error());
return$rs;
}function queryArray($sql){returnmysql_fetch_assoc($this->query($sql));
}functionexec($sql){$this->query($sql);
}/**
* @return bool - Was the saved array new or did it matched an existing one?
*/function saveArray($table, $arr){$atoms = array();
foreach($arras$k => $v){$atoms[] = $k."='".$v."'";
}$sql = "";
$new = !$arr['id'] || $arr['id'] == null;
if($new){// INSERTunset($arr['id']);
$sql = "INSERT INTO ".$table." SET ".implode(',',$atoms).";";
}else{// UPDATE$sql = "UPDATE ".$table." SET ".implode(',',$atoms)." WHERE id='".$arr['id']."';";
}$this->exec($sql);
return$new?mysql_insert_id():null;
}function &queryAllArray($sql){$res = array();
$rs =& $this->query($sql);
while($t = mysql_fetch_assoc($rs))$res[] = $t;
return$res;
}}?>
saveArray takes an array of key-value-pairs and saves it into the table. If the id is not set it inserts a new row, otherwise the existing row is updated.
Example
As the above makes no sense at all by itself here comes a bit of code I’m currently working on that uses it. First is a User-class that is used to represent the sites users. A user has many bank accounts:
Besides the normal variable and function declaration there are the functions that rely on setForeign, getForeign and getMany to work on the related objects. Pretty simple, huh?, Now to complete the relations I’ll just put the Entry class too, but by now you should be able to write it yourself
Ok, that’s it for now. Any feedback is very welcome And for all of those that don’t want to reconstruct my files using the above here’s all the code in their files:
I’m reallt thrilled about the post at the Ubuntu Blog:
So Dell emulated digg and put the idea to (good) use in letting people submit and vote for ideas to be implemented at Dell. The result was Dell Idea Storm.
Now maybe Dell regrets it, just a wee bit. You see, the popular requests page right now is dominated by Linux-oriented requests. The most popular idea is for machines with Linux (Ubuntu/OpenSUSE/Fedora) pre-installed. Followed closely by an idea to distribute PCs with OpenOffice preinstalled. There are popular ideas that suggest PCs without Windows installed, PCs with open-source Linux drivers etc.
Now, for Dell, it would be a small publicity setback if they do not act on at least a few of these ideas – them being the most popular ideas. It will be interesting to see how it develops. I hope Dell does not just seem to be attentive to customers, and actually gives them what they demand.
Could this finally be the end of half working Notebooks under Linux? That would be great news, especially after all the trouble I had (and still have) to get my Graphiccard running under OpenSuse 10.2.
[via the Ubuntu Blog]
About me
My name's Christian Decker, and I'm currently studying Computer Science at ETH Zurich.