Extend mysqli_result

前端 未结 2 1438
-上瘾入骨i
-上瘾入骨i 2020-12-21 10:17

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 quer

相关标签:
2条回答
  • 2020-12-21 11:12

    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
    {
        ...
    }
    
    0 讨论(0)
  • 2020-12-21 11:13

    Probably the simplest thing to do would be treat your MySQLiResult class as a decorator for mysqli_result. For example

    class MySQLiResult
    {
        private $result;
    
        public function __construct(\mysqli_result $result)
        {
            $this->result = $result;
        }
    }
    

    You could then proxy method calls to the internal result and decorate (add functionality) where required.

    0 讨论(0)
提交回复
热议问题