Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

php - Extend mysqli_result

I have extended PHP's mysqli class, which works fine. But how can I make it return a custom result object (or a boolean for insert/update/delete etc) when querying?

namespace MyApp;
class MySQLi extends mysqli {
    public function query($query, $resultmode = null) {
        // This needs to return a MySQLiResult or a boolean
    }
}
class MySQLiResult extends mysqli_result {
}

Doing this I can return a MySQLiResult object, but I can't figure out how to return a boolean for non select based queries:

public function query($query, $resultmode = null) {
    $this->real_query($query); 
    return new MySQLiResult($this);
}

Update:

This is what I ended up using:

class MySQLi extends mysqli {

    public function query($query, $resultmode = null) {
        $result = parent::query($query, $resultmode);
        return is_bool($result) ? $result : new MySQLiResult($result);
    }

}


class MySQLiResult {

    private $result;

    public function __construct(mysqli_result $result) {
        $this->result = $result;
    }

    public function __call($name, $arguments) {
        return call_user_func_array(array($this->result, $name), $arguments);
    }

    public function __set($name, $value) {
        $this->result->$name = $value;
    }

    public function __get($name) {
        return $this->result->$name;
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Phil's answer is OK, but it is possible to just extend MySQLi_Result by checking mysqli::field_count. Checkout the documentation for mysqli::field_count

This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

This is just what we needed.

public MySQL extends MySQLi
{
    public function query($query)
    {
        if ($this->real_query($query)) {
            if ($this->field_count > 0) {
                return new MySQL_Result($this);
            }
            return true;
        }

        throw new MySQL_Exception($this->error, $this->errno);
    }
}

Now you can extend your result class from MySQLi_Result and implement some useful interfaces like SeekableIterator so you can use foreach on your resultset:

class MySQL_Result extends MySQLi_Result implements Countable, SeekableIterator, ArrayAccess
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...