Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a database class in my user class

In my project I have a database class that I use to handle all the MySQL stuff. It connects to a database, runs queries, catches errors and closes the connection.

Now I need to create a members area on my site, and I was going to build a users class that would handle registration, logging in, password/username changes/resets and logging out. In this users class I need to use MySQL for obvious reasons... which is what my database class was made for.

But I'm confused as to how I would use my database class in my users class. Would I want to create a new database object for my user class and then have it close whenever a method in that class is finished? Or do I somehow make a 'global' database class that can be used throughout my entire script (if this is the case I need help with that, no idea what to do there.)

Thanks for any feedback you can give me.

like image 908
Josh Avatar asked Apr 05 '10 02:04

Josh


People also ask

Can database be a class?

Class diagrams do not show interaction with databases, since databases aren't classes.

What is a db class?

A database class is any class that extends the virtual class database . Once the required methods for dbread , etc. are defined or inherited, you can attach an object of the class and use the resulting database like any other. Notice that this is different from attaching a list-like object as a database.


1 Answers

Simple, 3 step process. 1/ Create a database object. 2/ Give it to your user class constructor. 3/ Use it in the user methods.

Little example.

File Database.class.php :

<?php
class Database{
  public function __construct(){
    // Connects to database for example.
  }

  public function query($sqlQuery){
    // Send a query to the database
  }
  [...]
}

In User.class.php :

<?php

class User{
  private $_db;
  public function __construct(Database $db){
    $this->_db = $db;
  }

  public function deleteUser(){
    $this->_db->query('DELETE FROM Users WHERE name = "Bobby"');
  }
}

Now, in userManager.php for example :

<?php
$db = new Database();
$user = new User($db);
// Say bye to Bobby :
$user->deleteUser();

If you want the current trendy name of this old technique, google "Dependency Injection". The Singleton pattern in php will fade away soon.

like image 126
Arkh Avatar answered Sep 19 '22 03:09

Arkh