Using my database class with other classes in my p

2019-07-04 01:23发布

问题:

I have a custom database class that I wrote myself, and I also have a user class and a site class.

The MySQL class has methods like this:

connect
query
clean
fetch

The user class:

register
login
logout
resetPass

The site class:

updateTopics
addTopic
addPost
addReply

etc.

These classes need to interface with a database, which is what I wrote the MySQL class for. But, I have no idea how to properly use the MySQL class with these classes. Do I define the class as global and just reference it in the other classes? Do I do something like:

$db = new MySQL();
$user = new User($db);

and then reference it like that?

Any help is appreciated, thank you. :)

回答1:

In addition to Daniel Vandersluis's answer: Instantiating the object within your class creates a strong dependency between those classes. You might instead be interested in dependency injection and inversion of control (+ ioc containers).

see:
http://en.wikipedia.org/wiki/Dependency_injection
http://martinfowler.com/articles/injection.html


btw: Do you really need your own MySQL class implementation? There are already so many database access and abstraction layers available. E.g. http://docs.php.net/pdo.



回答2:

you might be interested in stantiating the MySql class just one time. it prevents the connection to be opened and closed many times during execution. i like to use the Factory concept. it's a class that handle the instantiation of objects and you can write it to allow only one instance, following the Singleton concept.

someting like this:

class Factory {

    private static $objects = array();

    static function get_database() {

        if( ! isset(self::$objects['database']))
            self::$objects['database'] = new MySql();

        return self::$objects['database'];
    }
}

you would use like that:

$db = Factory::get_database();

note that it always return the same instance of MySql instead of creating new ones.

well, but it's just a very simple implementation of a Factory, just for understanding. it could be a lot better =]



回答3:

You could instantiate your MySQL class within your other classes, like so:

class User
{
  private $db;

  function __construct(...)
  {
    $this->db = new MySQL();
  }

  function accesses_database(...)
  {
    $this->db->query(...);
  }
}

And then reference $this->db inside your class when you want to access the database.

Also, if you want there to only be one instantiation of MySQL, you can make it a singleton.