扩展mysqli_result [英] Extend mysqli_result

查看:41
本文介绍了扩展mysqli_result的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我扩展了PHP的mysqli类,它可以正常工作.但是查询时如何使它返回自定义结果对象(或用于插入/更新/删除的布尔值)?

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 {
}

这样做我可以返回一个MySQLiResult对象,但是我不知道如何为非基于选择的查询返回一个布尔值:

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

更新:

这是我最终使用的:

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;
    }

}

推荐答案

可能最简单的方法是将您的MySQLiResult类视为mysqli_result的装饰器.例如

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.

这篇关于扩展mysqli_result的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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