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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.