Accessing Objects - Object to Object Communication
am 26.12.2009 22:38:44 von Allen McCabe--001636e0b95b27535c047ba87f4f
Content-Type: text/plain; charset=ISO-8859-1
I have a Database class that I instantiate with credential information. The
connect method connects and creates a resource by the name $link_id. So if I
do this:
$db = new Database($server, $user, $password, $database);
$db->connect();
To get the resource (for use by mysql_insert_id() for example), I use
$db->link_id, so to get the last inserted record:
$id = mysql_insert_id($db->link_id);
Now for my question:
I have another class for creating pages (content). I have a method called
newPage() that accepts 4 arguments: title, content, role_id, display, and
description.
If I need to get the ID of this new page (which is inserted to a mysql table
with an id field with auto_increment), how would I access my database
object? Here is what I have, but first I should provide a brief explanation:
I am trying to pass the database object to any other object that needs to
access the database so that I am assured a connection exists before using
any query methods. So instead of Database::query($sql), I have
$this->db->query($sql).
Here are some code snippets:
Content.class.php:
class Page {
private $db; // Contains reference to instance of the
Database class
private $notify; // Contains reference to instance of the
Notifier class
private $URL;
public function __construct($dbconnection, $root, $id = null)
{
$this->db = $dbconnection;
$this->notify = Notifier::getInstance();
$this->URL = $root . 'content/';
if (isset($id)) {
$result = $this->db->query('SELECT * FROM `content` WHERE
`page_id` = \''. $id .'\'');
$data = $this->db->fetch_array($result);
}
}
}
header.php:
require_once('lib/class/Database.class.php');
$db = new Database($dbhost, $dbuser, $dbpass, $dbname);
$db->connect();
require_once('lib/class/Notifier.class.php');
$notify = Notifier::getInstance(); // self instantiates
require_once('lib/class/Content.class.php');
$page = new Page($db, ROOT);
Does this look right? I don't think I've ever seen two -> operators together
like this before...
I don't want to keep connecting to the database, and more importantly, my
Notifier class should only be a single instance, so I need to be able to
amend to a static array variable in that class from within other classes.
Thanks for any help you can provide, and happy holidays!
--001636e0b95b27535c047ba87f4f--