The14thGOD Posted September 2, 2011 Share Posted September 2, 2011 I'm having difficulties forming a google query to get a result I want. Basically I want to have a db connection used by other classes. Someone showed me a month ago about a way to pass a db object to the class but said it wasn't the best method. So I'm trying to find a tutorial to get me on the right track. I'm new to OOP so if this sounds stupid I apologize. This is what I'm currently doing (passing the db connection to the object): <?php //config file $db = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME); //page $user = new user($db); //user class public function __construct($db){ $this->db = $db; } ?> Any help in the right direction would be greatly appreciated. Also if anyone knows any good books to purchase on walking through small projects that would be awesome. I bought PHP5 Objects, Patterns and Practices but that didn't really walk through a project. It did get to some complicated things (for me) that I think I can understand once I get smaller projects under my belt. Thanks, Justin Quote Link to comment https://forums.phpfreaks.com/topic/246248-using-db-connection-in-oop-guidence-needed/ Share on other sites More sharing options...
KevinM1 Posted September 2, 2011 Share Posted September 2, 2011 Look up dependency injection/inversion of control. Essentially, you have a class called a dependency injection container which takes an object (in your case, your User object) and the dependency it relies on (the db connection), and does the dirty work of injecting that dependency into the object for you. I believe Symfony has a DI container you can plug into your system with minimal fuss. Quote Link to comment https://forums.phpfreaks.com/topic/246248-using-db-connection-in-oop-guidence-needed/#findComment-1264670 Share on other sites More sharing options...
The14thGOD Posted September 2, 2011 Author Share Posted September 2, 2011 Thanks! I think I found a good tutorial on it. Looks simple enough. (for those who may stumble here: http://www.potstuck.com/2009/01/08/php-dependency-injection/ ) Quote Link to comment https://forums.phpfreaks.com/topic/246248-using-db-connection-in-oop-guidence-needed/#findComment-1264739 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.