Can someone please explain ‘re-usable structures’ for me? I was working on making some db objects in php, but was told I was using too much processing from the computer cause I made stuff to complicated with the below objects:
My DB objects:
$db = new Database; $db->db_connect(); $post_content = new DbSelect; $post_content->select('id', 'title', 'firstName', 'created', 'catName', 'tagName'); $post_content->from('content'); $post_content->join('inner'); $post_content->on('category','cat_id','id'); $post_content->where('id','1'); $post_content->order('created'); $db->db_close();
Normal PHP:
mysql_connect(); mysql_db_select(); $query = 'SELECT id, title, s_name, created, cat_name, tag_name FROM content JOIN INNER category, cat_id, id WHERE id=1 ORDER created'; mysql_close();
So to reiterate my questions: 1. A quick explanation of re-usable structures? 2. why is the first method using objects ‘wrong’?
please note: I’ll be googling this as well as hoping for feedback I know there a ‘tools’ like Zend and other’s that have plenty of db objects built into them, but I’m trying a DIY approach
I’m not sure where to start on this one. Object Oriented design is not a trivial subject, and there are many ways it can go wrong.
Essentially, you want to try to make logical indepedent objects in your application such that you can swap them out for other modules with the same interface, or reuse them in future projects. In your database example, look at PEAR::MDB2. PEAR::MDB2 abstracts the database drivers away from your application so that you don’t need to worry about which specific database you’re using. Today, you might be using MySQL to run your site. Tomorrow, you might switch to Postgresql. Ideally, if you use a proper OO design, you shoudn’t need to change any of your code to make it work. You only need to swap out the database layer for another. (Pear::MDB2 makes this as simple as changing your db connect string)
May I suggest reading Code Complete by Steve McConnell. There’s a whole chapter on Classes. While the examples are primarily C++, the concepts can be applied to any programming language, including PHP.