Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a PHP user class extend a database class?

I am not sure if this is totally the wrong thing to do, so I am looking for a bit of advice.

I have set up a database class with the constructor establishing a PDO connection to a MySQL database.

I've been looking at singletons and global variables, but there always seems to be someone who recommends against either/or.

I'm experimenting with a user class which extends the database class, so I can call upon the PDO functions/methods but maintain separate user class code. Is this a stupid thing to do?

like image 329
tommyd456 Avatar asked Oct 19 '11 20:10

tommyd456


People also ask

What is the purpose of extends in PHP?

The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from.

Can we extend private class in PHP?

Yes, that's the sane method to do this. Better method is to use protected in the parent class ;) that way it stays private from outside, but "child" class can access it.


2 Answers

You should generally pass a connection into your user, so your user class would take a database type object into its constructor and then use that database object to execute queries against the database. That way your data access logic remains separate from your business logic. This is called composition, as opposed to what you're talking about, which is inhertance.

If you really wanted to be technical, it would be best to have a user object with nothing but public variables, and then you would use a 'service' to implement your business logic.

class UserService implements IUserService
{
    private $_db;
    function __construct(IDb $db) {
        $this->_db = db;
    }

    function GetAllUsers() {
        $users = Array();

        $result = $this->_db->Query("select * from user")

        foreach($result as $user) {

            //Would resolve this into your user domain object here
            users[] = $user;
        }
        return users;
    }
}
like image 145
nathan gonzalez Avatar answered Oct 18 '22 00:10

nathan gonzalez


Well, ask yourself if User is a special case of Database. I'm not sure how others perceive it, but I would be kind of offended. I think what you need is to read about the Liskov substitution principle.

As for solving your "people tell me that globals are bad" issue, here are two videos you should watch:

  • The Clean Code Talks - Don't Look For Things!
  • The Clean Code Talks - Global State and Singletons
like image 44
tereško Avatar answered Oct 18 '22 02:10

tereško