PHP用户类应该扩展数据库类吗? [英] Should a PHP user class extend a database class?

查看:37
本文介绍了PHP用户类应该扩展数据库类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是否完全是错误的事情,所以我正在寻找一些建议.

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

我已经用构造函数建立了一个数据库类,该构造函数建立了 PDO 连接MySQL数据库.

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.

我正在尝试扩展数据库类的用户类,因此我可以调用PDO函数/方法,但要维护单独的用户类代码.这是愚蠢的事吗?

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?

推荐答案

通常应该将连接传递给用户,因此您的用户类会将数据库类型对象放入其构造函数中,然后使用该数据库对象执行针对数据库.这样,您的数据访问逻辑便与业务逻辑保持分离.这就是所谓的合成",与您所说的固有"相反.

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;
    }
}

这篇关于PHP用户类应该扩展数据库类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆