 |
| Coding Forum Problems with your code? Discuss coding issues, including JavaScript, PHP & MySQL, HTML & CSS, Flash & ActionScript, and more. |
|
 |
01-31-2007, 01:47 AM
|
#1 (permalink)
|
|
Contributing Member
Join Date: 10-12-03
Location: California
Posts: 201
Latest Blog: None
|
associative array vs object
I'm pretty new to OOP, and I've got a handle on the concept... but I'm still having trouble with actually using objects. I'm unsure if that's actually what I want in my current situation.
I'm re-writing an old game I made a few years back, and before what I would do to display a player's data on his "hq" page would be to query his id in the players table, and assign all that data to a $players[] array.
Now, I'm thinking it may be better to create a player object. But I'm not quite sure how to go about putting the info from a player's row in the db into the player object.
So far, this is what I have:
Code:
class player {
var $username;
var $last_login;
function player($playerName, $playerLastLogin) {
$this->username = $playerName;
$this->last_login = $playerLastLogin;
}
So... when i instantiate a player, I need to pass it those 2 values, but it seems really strange to pull those values from the db into a variable just to pass them along to an object variable...
Is this making any sense? I don't quite know how to gracefully populate a player object with data from the players table in the db. I know just using an array like before would work for now, but I'm sure a player object is the better way to go.
|
|
|
01-31-2007, 02:00 AM
|
#2 (permalink)
|
|
Senior Member
Join Date: 01-02-07
Location: PA, USA
Posts: 191
Latest Blog: None
|
I like arrays, I think they are better than objects. I started my programming career in C, then C++, then Java, now PHP, I love just using $arr = mysql_fetch_array($val); it's so useful. And way easier.
|
|
|
01-31-2007, 02:14 AM
|
#3 (permalink)
|
|
Contributing Member
Join Date: 10-12-03
Location: California
Posts: 201
Latest Blog: None
|
Yeah, that's what appealing to me right now. It seems so clean to just create an array to represent a row, which in turn represents a player's basic information.
But at the same time I really like the idea of having objects that not only represent something, but can also carry out tasks.
Although, I suppose I could easily enough write functions that take an array as a parameter.
Decisions... =/
|
|
|
01-31-2007, 03:25 AM
|
#4 (permalink)
|
|
Moderator
Join Date: 01-23-07
Location: Buenos Aires, Argentina
Posts: 1,187
|
You can write a small script to automatically create objects from the results of a database query.
I have a database wrapper which I wrote for PHP and works like a recordset. Besides, I create classes to represent entities.
My class looks like this:
PHP Code:
class Player{
function get($filters){
$sql = "SELECT... from player ";
if ($filters) $sql .= "WHERE " . $filters;
$rData = SQL::query($sql);
return($rData);
}
}
Then my frontend code looks like this:
PHP Code:
$rData = Player::get("name LIKE 'Cris%'");
for($i=0;$i<$rData->quantity();$i++){
echo( $rData->field("name",$i) . "<br/>" );
}
I used 3 classes there:
Class Player, which represents the player entity.
Class SQL, that acts like a database wrapper.
Class Data, that works like a recordset to manage the data.
I can post the code of these classes if you want. Let me know!
__________________
Hades,
Ancient god, King of the Nether World, and Guardian of the Dead.
...and on my free time I'm also a web developer, contact me if you need one!
|
|
|
01-31-2007, 11:25 AM
|
#5 (permalink)
|
|
Contributing Member
Join Date: 10-12-03
Location: California
Posts: 201
Latest Blog: None
|
It would be helpful if you could. =) I've got the idea of what you're saying, but I wouldn't know how to start implementing it.
|
|
|
01-31-2007, 06:59 PM
|
#6 (permalink)
|
|
Moderator
Join Date: 01-23-07
Location: Buenos Aires, Argentina
Posts: 1,187
|
OK, here we go...
First, you have three files, one that acts like a database connector, another that acts as a dataaccess wrapper and the last one will work as a recordset.
Database.php
PHP Code:
class Database{ function connect( $hostname, $user, $password, $db ) { static $connected; if ($connected) return; $connId = @mysql_connect($hostname, $user, $password) or die('Cannot connect to database server'); @mysql_select_db($db) or die('The database is currently down'); $connected = true; return $connId; } function close(){ mysql_close(); return; } }
SQL.php
PHP Code:
class SQL { /** * @desc executes a single DDL query * * @param string $sql * @param integer $queryType * @param integer-pointer $id * @param string-pointer $error * @return $result */ function execute($sql, $queryType, &$id,&$error,$log=true) { Database::connect("host","username", "password", "database"); $sqlTransact = $sql; $result = mysql_query($sql); if($queryType=="DBINSERT") { $id = @mysql_insert_id(); } if (mysql_errno()){ $error = mysql_error()."\nQuery: " . $sql; } Database::close(); return $result; } /** * @desc executes a single DML query * * @param string $sql * @return Data $rs */ function query($sql) { Database::connect($_SESSION['sess_conf']['db_hostname'],$_SESSION['sess_conf']['db_username'], $_SESSION['sess_conf']['db_password'], $_SESSION['sess_conf']['db_database']); $rs = mysql_query($sql) or die(mysql_error() . "<br><b>QUERY</b>:<br>" . nl2br($sql)); if(mysql_num_rows($rs) >0) { for($i=0; $i< mysql_num_fields($rs); $i++) $fields[mysql_field_name($rs, $i)] = $i;
while ($row = mysql_fetch_row($rs)) $vec[] = $row;
mysql_free_result($rs); Database::close(); return new Data($fields, $vec); } Database::close(); return new Data(); } }
Data.php
PHP Code:
class Data { var $_fields = ""; var $_data = ""; function Data($_fields=Array(), $_data=Array()) { $this->_fields = $_fields; $this->_data = &$_data; } /** * count the result * * @return int */ function quantity() { return count($this->_data); } /** * count columns * * @return int */ function quantityFields() { return count($this->_fields); } /** * get the Field * * @param String $field * @param int $row * * @return mixed */ function field($field, $row) { $value = $this->_data[$row][$this->_fields[$field]]; return $value; } /** * get the colum name * * @param String $fieldCol * * @return String */ function fieldNameByPosition($fieldCol) { $aFields = array_keys($this->_fields); return $aFields[$fieldCol]; } /** * get the field position by name * * @param String $name * @return int */ function getFieldPositionByName($name) { if (!array_key_exists($name, $this->_fields)) { return false; } return $this->_fields[$name]; } /** * get the Field * * @param int $field * @param int $row * * @return mixed */ function fieldByPosition($field, $row) { $value = $this->_data[$row][$field]; return $value; } /** * make an array. * * @return Array */ function &getArray(){ $aResponse = array(); $keys = array_keys($this->_fields); for($i=0;$i<count($this->_data);$i++){ $aResponse[$i] = array(); foreach($keys as $k){ $aResponse[$i][$k] = $this->_data[$i][$this->_fields[$k]]; } } return ($aResponse); } function getColsNames() { return array_keys($this->_fields); } }
Then, you will have a class for each entity in your system, if you need a Player entity, my class looks like the one as follows:
Player.php
PHP Code:
/** * Class Player * Class for player management * * Related Table: player * Alias: pl * ID: idPlayer * Label: name * Relative Path: * * Author: Chris @ Liberty Web Systems * Date: Wed Jan 31 22:38:39 ART 2007 **/ class Player { /** * Returns a filtered list from player (pl)... * * @param integer $id * @param string $filters * @param string $order * @param string $limit * @return Data */ function get($id="",$filters="",$order="",$limit=""){ global $_SYS; $sql = " SELECT pl.idPlayer, pl.* FROM player pl WHERE 1 "; if ($id) $sql .= " AND pl.idPlayer = '".$id."'"; if ($filters) $sql .= "AND " . $filters; if ($order) $sql .= " ORDER BY " . $order; if ($limit) $sql .= " LIMIT $limit"; $rData = SQL::query($sql); return ($rData); } /** * Returns the count of registries from a filtered list * * @param integer $id * @param string $filters * @return integer */ function countRegistries($id="",$filters=""){ global $_SYS; $sql = " SELECT COUNT(pl.idPlayer) as cnt FROM player pl WHERE 1 "; if ($id) $sql .= " AND idPlayer = '".$id."' "; if ($filters) $sql .= " AND " . $filters; $rData = SQL::query($sql); return ($rData->field("cnt",0)); } /** * Inserts a new registry into player * * @param array $aData * @return integer */ function insert($aData){ $sql = " INSERT INTO player ( name, dateAdded, team, points ) VALUES ( '".$aData['name']."', '".$aData['dateAdded']."', '".$aData['team']."', '".$aData['points']."' ) "; SQL::execute($sql,DBINSERT,$id,$error); return($id); } /** * Modifies a registry from player * * @param integer $id * @param array $aData * @return integer */ function update($id,$aData){ $sql = " UPDATE player SET name = '".$aData['name']."', dateAdded = '".$aData['dateAdded']."', team = '".$aData['team']."', points = '".$aData['points']."' WHERE idPlayer = '".$id."'"; SQL::execute($sql,"DBUPDATE",$id,$error); } /** * Deletes a registry from player * * @param integer $id */ function delete($id){ global $_SYS; $sql = "DELETE FROM player WHERE idPlayer = $id"; SQL::execute($sql,"DBDELETE",$id,$error); } }
After including these files one can start programming  (okok that was a joke!)
Lets suppose that you need to display a list of players, you can do something like this:
PHP Code:
include("Database.php"); include("SQL.php"); include("Data.php"); include("Player.php");
//Dummy Data. $idPlayer = 1;
//a simple, "select all" query. $rDataAll = Player::get();
//select only one player. $rDataOnlyOne = Player::get($idPlayer);
//select by filter $rDataFiltered = Player::get(false," points > '100'");
/*FOR FURTHER INFORMATION ON HOW TO USE THE GET FUNCTION, READ ITS PROTOTYPE ON THE PLAYER CLASS*/
Now you have three recordsets, you can read them with this code
PHP Code:
for($i=0;$i<$rDataAll->quantity();$i++){ echo(" Name = ".$rDataAll->field("name",$i)." <br/> Added = ".$rDataAll->field("dateAdded",$i)." <br/> Team = ".$rDataAll->field("team",$i)." <br/> Points = ".$rDataAll->field("points",$i)." <br/> <hr/> "); }
To insert a registry into the player table, you can use this code:
PHP Code:
$aData = array( "name"=>"Jack", "dateAdded"=>"2007-01-01", "team"=>"blue", "points"=>1000 );
Player::insert($aData);
You can do something similar in order to update and delete registries, take a look at the prototypes of the Player class (documentation is very useful  )
This is how I work, however, any suggestion will be accepted. Post your questions if you need any kind of help, we are all here to learn!
__________________
Hades,
Ancient god, King of the Nether World, and Guardian of the Dead.
...and on my free time I'm also a web developer, contact me if you need one!
|
|
|
01-31-2007, 07:56 PM
|
#7 (permalink)
|
|
Contributing Member
Join Date: 10-12-03
Location: California
Posts: 201
Latest Blog: None
|
Well holy crap. That's quite... pretty
Thanks a ton, I'm gonna play around with all that to get a feel for how it all works. I'm pretty impressed, that's rather clean code you've got there 
|
|
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
All times are GMT -7. The time now is 04:51 PM.
© Copyright 2008 V7 Inc Powered by vBulletin Copyright © 2000-2009 Jelsoft Enterprises Limited.
|
|
|