在我的用户类中使用数据库类 [英] Using a database class in my user class

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

问题描述

在我的项目中,我有一个数据库类,我用来处理所有的MySQL东西。它连接到数据库,运行查询,捕获错误并关闭连接。

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.

现在我需要在我的网站上创建一个成员区域,用户类将处理注册,登录,密码/用户名更改/重置和注销。在这个用户类中,我需要使用MySQL显而易见的原因...这是我的数据库类。

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.

推荐答案


1 /创建数据库对象。
2 /把它给你的用户类构造函数。
3 /在用户方法中使用它。

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

小例子。

File Database.class .php:

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
  }
  [...]
}

在User.class.php中:

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"');
  }
}



现在,在userManager.php中, p>

Now, in userManager.php for example :

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

如果你想要这个老技术的当前时髦的名称,google依赖注入。 php中的Singleton模式很快就会消失。

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

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

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