在我的项目中使用我的数据库类与其他类 [英] Using my database class with other classes in my project

查看:99
本文介绍了在我的项目中使用我的数据库类与其他类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自己写的自定义数据库类,我也有一个用户类和一个网站类。

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

MySQL类有这样的方法: / p>

The MySQL class has methods like this:

connect
query
clean
fetch

用户类:

register
login
logout
resetPass

网站类:

updateTopics
addTopic
addPost
addReply

等。

这些类需要与数据库连接,这是我写的MySQL类。但是,我不知道如何正确使用MySQL类与这些类。我把类定义为全局的,只是引用它在其他类?我做的事情:

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

然后像这样引用?

任何帮助,谢谢,谢谢。 :)

Any help is appreciated, thank you. :)

推荐答案

除了Daniel Vandersluis的回答:
实例化类中的对象,类。您可能会对控制(+ ioc容器)的依赖注入和反转感兴趣。

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).

请参阅:

http://en.wikipedia.org/wiki/Dependency_injection

http://martinfowler.com/articles/injection.html

btw:你真的需要你自己的MySQL类实现吗?已经有这么多的数据库访问和抽象层可用。例如。 http://docs.php.net/pdo

这篇关于在我的项目中使用我的数据库类与其他类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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