在PHP中相互扩展的功能更高效?

时间:2017-11-18 10:23:15

标签: php

我的用户类中有以下功能来获取用户ID,名称和电子邮件:

public function getUserID(){
    $stmt = $this->conn->prepare("SELECT userID FROM [DataBase].[dbo].[users] WHERE userID=:uid");
    $stmt->execute(array(":uid"=>$_SESSION['userSession']));
    $userID=$stmt->fetch(PDO::FETCH_ASSOC);
    echo $userID['userID'];
}

public function getUserName(){
    $stmt = $this->conn->prepare("SELECT userName FROM [DataBase].[dbo].[users] WHERE userID=:uid");
    $stmt->execute(array(":uid"=>$_SESSION['userSession']));
    $userName=$stmt->fetch(PDO::FETCH_ASSOC);
    echo $userName['userName'];
}

public function getUserEmail(){
    $stmt = $this->conn->prepare("SELECT userEmail FROM [DataBase].[dbo].[users] WHERE userID=:uid");
    $stmt->execute(array(":uid"=>$_SESSION['userSession']));
    $userEmail=$stmt->fetch(PDO::FETCH_ASSOC);
    echo $userEmail['userEmail'];
}

但我只是觉得有更好的方法可以做到这一点,因为看起来浪费资源来做3个几乎相同的查询。

有没有办法我可以执行一次查询以选择所有3个字段并且有一个函数来获取相关数据?

2 个答案:

答案 0 :(得分:1)

在编写代码之前,您可能需要多考虑一下......

public function getUser(){
    $stmt = $this->conn->prepare("SELECT * FROM [DataBase].[dbo].[users] WHERE userID=:uid");
    $stmt->execute(array(":uid"=>$_SESSION['userSession']));
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // get attributes : $user['userName'] ....
    return $user;
}

答案 1 :(得分:1)

请改为尝试:

class User {
    private $user;
    public function __construct($id, $conn) {
            $stmt = $conn->prepare("SELECT * FROM [DataBase].[dbo].[users] WHERE userID=:uid");
            $stmt->execute(array(":uid"=>$id));
            $this->user = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    public function getUserId() {
           return $this->user["userID"];
    }
    // more methods as well or a generic __call e.g.

    public function __call($name, $args) {
         if (substr($name, 0, 3) === "get") { // e.g. getUserName will get userName
             return $this->user[lcfirst(substr($name,3))];
         }
    }

}

然后你可以这样做:

 $user = new User($_SESSION["userSession"], $this->conn);

如果需要,您甚至可以在会话中保留模型:

 $_SESSION["usermodel"] = $user;