Jump to content

using db connection in oop, guidence needed


The14thGOD

Recommended Posts

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.