Home arrow PHP arrow Page 2 - A Persistent Class in Action

Review: creating a database-driven persistent class - PHP

If youíre a PHP developer who wants to learn how to create objects that can maintain their state through different HTTP requests, either by using cookies, plain text files or MySQL database tables, then donít look any further because youíve come to the right place. Welcome to the last part of a six-part series on building persistent objects in PHP 5. This tutorial series introduces the key concepts that surround the creation of persistent objects, and complements the corresponding theory with copious code samples.

TABLE OF CONTENTS:
  1. A Persistent Class in Action
  2. Review: creating a database-driven persistent class
  3. Spawning a persistent object from the User class
  4. Retrieving properties of a persistent object on a different web page
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
September 30, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To understand how the pair of sample classes mentioned in the introduction can be put to work in tandem to create a persistent object whose properties will be saved to a MySQL table, it'd be useful to recall how these classes were initially defined in the preceding tutorial.

Here's the source code that corresponds to the MySQL abstraction class. It's responsible for performing queries against a selected database. Take a look at its short definition:

class MySQL

{

private $result = NULL;

private $link = NULL;

 

// connect to MySQL

public function __construct($host, $user, $password, $database)

{

if (FALSE === ($this->link = mysqli_connect($host, $user, $password, $database)))

{

throw new Exception('Error : ' . mysqli_connect_error());

}

}

 

// perform query

public function query($query)

{

if (is_string($query) AND !empty($query))

{

if (FALSE === ($this->result = mysqli_query($this->link, $query)))

{

throw new Exception('Error performing query ' . $query . ' Error message :' .mysqli_error($this->link));

}

}

}

 

// fetch row from result set

public function fetch()

{

if (FALSE === ($row = mysqli_fetch_assoc($this->result)))

{

mysqli_free_result($this->result);

return FALSE;

}

return $row;

}

 

// get insertion ID

public function getInsertID()

{

return mysqli_insert_id($this->link);

}

// count rows in result set

public function countRows()

{

if ($this->result !== NULL)

{

return mysqli_num_rows($this->result);

}

}

// implement destructor to close the database connection

function __destruct()

{

mysqli_close($this->link);

}

}

Since in the previous installment I covered in detail how the above "MySQL" class works, I'm not going to bore you with redundant explanations of the way that each of its methods have been implemented. The only thing worth noting here is that the class packages enough functionality for connecting to MySQL and running queries, counting the number of rows in a result set, and so forth.

Now it's time to show the definition of the persistent class, which I called "User," since it stores user-related data on a specified MySQL table.

The complete signature of this sample class is as follows:

class User

{

private $data = array();

private $id = 1;

private $db = NULL;

 

// constructor

public function __construct(MySQL $db, $id = NULL)

{

$this->db = $db;

if ($id !== NULL)

{

$this->id = $id;

 }

$this->db->query('SELECT * FROM users WHERE id=' . $this->id);

$this->data = $this->db->fetch();

}

 

// set undeclared property

public function __set($property, $value)

{

if ($property !== 'name' and $property !== 'email')

{

return;

}

$this->data[$property] = $value;

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->data[$property]) === TRUE)

{

return $this->data[$property];

}

}

 

// save class properties to MySQL table

public function __destruct()

{

$this->db->query("UPDATE users SET name = '$this->name', email = '$this->email' WHERE id = $this->id");

}

}

Even though the definition of the previous "User" class looks pretty skinny and compact, it performs a few interesting tasks that are worth a closer look. As you can see, aside from implementing the "__set()" and "__get()" PHP 5 magic methods, which permit it to handle undeclared properties on the fly, the class also uses its constructor to retrieve those properties from a fictional "users" MySQL table.

Next, these properties are stored in the internal $data array, which lets the destructor save them again to the "users" table, right before the PHP interpreter finishes executing the calling script.

The question that comes up at this point is: do you have a vague idea of how to create a persistent object with the two classes shown earlier? I'm sure you do! Nonetheless, to dissipate any doubts that you may have on this subject, in the course of the following section I'm going to create a brand new example that will put these classes together so you can see them in action. 

To learn how this particular example will be developed, please click on the link that appears below and keep reading.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: