On Saturday 26 December 2009 3:38:44 pm Allen McCabe wrote: > 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! Chaining multiple -> operators together like that is totally fine, and what you're doing here with the database is a good example of simple dependency injection. In fact, you should do the same with the notifier class and pass it into the constructor of Page as well rather than making it a syntactic singleton. For extra credit, wrap all of that into a factory function or factory object: function create_page($root) { $db = create_your_db(); $notifier = create_your_notifier(); return new Page($db, $notifier, $root); } $new_page = create_page($my_root); And the db and notifier routines can be as simple or complex as needed for your use case. They could be singletons themselves, but don't have to be. And in either case, Page() now doesn't know or care so you can change your mind without affecting Page. Page is now loosely coupled, and all is right with the world. -- Larry Garfield larry@xxxxxxxxxxxxxxxx -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php