Home › My Profile - Proof of Concept Module › My Profile - Object Class Pattern
My Profile - Object Class Pattern
in
A simple object pattern for our custom data.
The following listing demonstrates 2 classes:
- A data object called "my_profile", Stores a single instance of the data. Uses simple getter/setter methods.
- A data access object. Provides methods to store and retrieve "my_profile" data from the system database. We also include some methods the retrieve data related to my_profile (e.g. the users table).
class my_profile { protected $alias; protected $uid; protected $id; function __construct() { } public function getAlias() { return $this->alias; } public function setAlias($alias) { $this->alias = $alias; } public function getUid() { return $this->uid; } public function setUid($uid) { $this->uid = $uid; } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } } class dbMy_profile { function __construct() { } function insert($myprofile) { drupal_write_record('my_profile', $myprofile); return $myprofile; } function delete($id) { $dbResult = db_query('delete from {my_profile} where uid = %d', $id); return $dbResult; } function update($myprofile) { $dbResult = db_query("update {my_profile} set alias = '%s' where id= %d", $myprofile->getAlias(),$myprofile->getId()); return $dbResult; } function get($id) { $mp = new my_profile(); $dbResult = db_query('select alias, uid from {my_profile} where id = %d',$id); if ($dbResult) { $obj = db_fetch_object($dbResult); $mp->setAlias($obj->alias); $mp->setId($id); $mp->setUid($obj->uid); } return $mp; } function getByUid($uid) { $mp = new my_profile(); $dbResult = db_query('select alias, id from {my_profile} where uid = %d',$uid); if ($dbResult) { $obj = db_fetch_object($dbResult); $mp->setAlias($obj->alias); $mp->setId($obj->id); $mp->setUid($uid); } return $mp; } function getUsersWithoutAlias() { $sql = "select name, uid from {users} where uid not in (select a.uid from users a join {my_profile} b on a.uid = b.uid) and name <> ''"; $list = array(); $dbResult = db_query($sql); if ($dbResult) { while($obj = db_fetch_object($dbResult)) { $list[$obj->uid] = $obj->name; } } return $list; } }
Explanation: For "My Profile", we add one database table. That table is added in the installation routine (installation routine detailed later). The new database table is called: my_profile, it contains 3 fields: id, uid and alias.
- id -- an integer that is generated by the database engine. The "id" field serves as a unique identifier for each record.
- uid -- this is the users table foreign key. We use the "uid" field to relate our custom record to a specific user.
- alias -- a simple text field.



