将 MySQL 查询转换为对象的最佳方法

发布于 2024-10-12 09:08:38 字数 137 浏览 3 评论 0原文

我有一个用户表,其中包含一堆我想在登录用户的 mysql 查询中访问的列。最终,我希望这些列中的值形成一个 User 对象。是否有一个标准函数可以执行此操作,或者我基本上需要将查询的每个值传递到新的 User 语句中,以便将它们传递给 User 类的构造函数?

I have a user table that contains a bunch of columns that I want to access in a mysql query for the logged in user. Ultimately, I want the values in these columns to form a User object. Is there a standard function for doing this, or do I basically need to pass each value of the query into a new User statement so that they are passed to the User class's constructor?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

古镇旧梦 2024-10-19 09:08:43

您应该查看 mysqli_result::fetch_object。您还可以查看 PHP 的 PDO 扩展

桌子

首先,了解你的桌子。

CREATE TABLE `user` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(256) NOT NULL,
    `password` VARCHAR(256) NOT NULL,
     PRIMARY KEY (`id`)
);

域对象

创建您的对象。您不需要定义任何这些字段,因为默认情况下它们将作为 public 添加到您的对象中,但对于以后可能维护您的代码的任何人来说都是清楚的;为了清晰起见定义字段。由于字段是私有的,因此访问器和修改器是必需的。

class User {
    private $id;
    private $username;
    private $password;

    public function __construct($id, $username, $password) {
        $this->id = $id;
        $this->username = $username;
        $this->password = $password;
    }

    public function getId() { return $this->id; }
    public function setId($id) { $this->id = $id; }

    public function getUsername() { return $this->username; }
    public function setUsername($username) { $this->username = $username; }

    public function getPassword() { return $this->password; }
    public function setPassword($password) { $this->password = $password; }
}

查询

创建查询类。其中很多都是样板代码,可以将其提取到抽象类中。

class UserQuery {
    public function create() {
        return new self();
    }

    public function findById($id) {
        $user = null;
        $conn = mysqli_connect("localhost", "root", "pass", "company_db");

        if ($conn->connect_error)
            die("$conn->connect_errno: $conn->connect_error");

        $query = "SELECT * FROM `user` WHERE `id` = ?";
        $stmt = $conn->stmt_init();

        if (!$stmt->prepare($query)) {
            print "Failed to prepare statement\n";
        } else {
            $stmt->bind_param('i', $id); 
            $stmt->execute();
            $result = $stmt->get_result();
            $obj = $result->fetch_object();

            return new User($obj->id, $obj->username, $obj->password);
        }

        $stmt->close();
        $conn->close();

        return null;
    } 
}

user 表中获取User 对象。

$user = UserQuery::create()->findById(1);
printf("Found user: %s", $user->getUsername());

You should checkout mysqli_result::fetch_object. You could also look into PHP's PDO extension.

Table

First, know your table.

CREATE TABLE `user` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(256) NOT NULL,
    `password` VARCHAR(256) NOT NULL,
     PRIMARY KEY (`id`)
);

Domain Object

Create your object. You do not need to define any of these fields, because they will be added to your object as public by default, but it is clear to anyone who may maintain your code later; to define the fields for clarity. The accessors and mutators are necessary since the fields are private.

class User {
    private $id;
    private $username;
    private $password;

    public function __construct($id, $username, $password) {
        $this->id = $id;
        $this->username = $username;
        $this->password = $password;
    }

    public function getId() { return $this->id; }
    public function setId($id) { $this->id = $id; }

    public function getUsername() { return $this->username; }
    public function setUsername($username) { $this->username = $username; }

    public function getPassword() { return $this->password; }
    public function setPassword($password) { $this->password = $password; }
}

Query

Create a query class. A lot of this is boilerplate code, which can be extracted out into an abstract class.

class UserQuery {
    public function create() {
        return new self();
    }

    public function findById($id) {
        $user = null;
        $conn = mysqli_connect("localhost", "root", "pass", "company_db");

        if ($conn->connect_error)
            die("$conn->connect_errno: $conn->connect_error");

        $query = "SELECT * FROM `user` WHERE `id` = ?";
        $stmt = $conn->stmt_init();

        if (!$stmt->prepare($query)) {
            print "Failed to prepare statement\n";
        } else {
            $stmt->bind_param('i', $id); 
            $stmt->execute();
            $result = $stmt->get_result();
            $obj = $result->fetch_object();

            return new User($obj->id, $obj->username, $obj->password);
        }

        $stmt->close();
        $conn->close();

        return null;
    } 
}

Fetch a User object from the user table.

$user = UserQuery::create()->findById(1);
printf("Found user: %s", $user->getUsername());
憧憬巴黎街头的黎明 2024-10-19 09:08:42

mysql_fetch_object() 允许您指定一个类名,以便根据您的结果构造该类的实例:

$result = mysql_query($sql); // Error handling not included

if (mysql_num_rows($result) == 1) {
    $user = mysql_fetch_object($result, 'User');
}

除非您指定与 SELECT 查询中列出的列相对应的属性及其访问修饰符,否则它们将默认为 <代码>公共。

对象的构造函数在填充其属性后被调用。您想要执行的任何更改或附加任务都可以在构造函数中执行。

mysql_fetch_object() allows you to specify a class name so instances of that class will be constructed from your results:

$result = mysql_query($sql); // Error handling not included

if (mysql_num_rows($result) == 1) {
    $user = mysql_fetch_object($result, 'User');
}

Unless you specify the properties and their access modifiers that correspond to the columns listed in your SELECT query, they will default to public.

Your object's constructor is called after populating its properties. Any changes or additional tasks you want to perform may be performed in the constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文