返回对象(PHP最佳实践)

时间:2016-05-24 23:10:47

标签: php oop

在编写PHP OOP代码时,为了将各种类的“返回对象”用于传递食物链中的成功,失败,错误消息等,这是一种好/可接受/明智的做法吗?

我现在拥有的例子:

“返回对象”:

class JsqlReturn{
    public $response;
    public $success;
    public $debug_message;
    public $mysqli_result_obj;
    function __construct($bool=false,$debug_message=NULL,$res=NULL,$mysqli_result_obj=NULL){
        $this->success = $bool;
        $this->response = $res;
        $this->debug_message = $debug_message;
        $this->mysqli_result_obj = $mysqli_result_obj;
    }
}

使用示例方法的主类:

class Jsql{

    function connect($host,$username,$password,$database){ #protected?
        $this->db = new \mysqli($host,$username,$password,$database);
        if($this->db->connect_errno){
            return new JsqlReturn(false,"Connection failed: (".$this->db->connect_errno.") ".$this->db->connect_error);
        }
        else{
            return new JsqlReturn(true,NULL,"Connection success.");
        }
    }

}

实施

$db = new Jsql;
$return = $db->connect(...);
if($return->success){ echo $return->response; }
else{ echo $return->debug_message; }

我知道在这里使用连接示例是微不足道的,但我的问题与编码实践有关。

我在这种做法中的主要目标是确保我在如何处理方法的返回数据方面保持一致。

注意:怜悯。这是我在这里的第一个问题。 :)我已经慢慢地自学了,从几年前涉足的正常路线走向程序性的PHP并最终进入OOP。

1 个答案:

答案 0 :(得分:0)

这对我来说似乎是一种非常合理的方法。

being consistent in how I am handling the return data from methods而言,您可以使响应类实现响应接口,然后您就会知道所有类型的响应类都遵循相同的规则,因此您可以安全地在整个申请中使用它:

interface MyResponseInterface
{
    public function getResponse();
    public function getDebugMessage();
    public function getSuccess();
    public function getMysqliConnection();
}

class JsqlResponse implements MyResponseInterface
{
    // ...
}

然后你知道,只要你的对象返回JsqlResponseTimeResponseMemberResponse等,他们都会实现你的响应界面,因此你的公众获取者将会可用,例如:

/** @var MyResponseInterface $return */
$return = $db->connect(...);
if($return->getSuccess()) {
    echo $return->getResponse();
} else {
    echo $return->getDebugMessage();
}

注意:在我可以返回的各种响应的示例中,我想(假设)时间和成员可能不需要MySQL连接,所以也许你可以省略它MyResponseInterface并为数据库连接创建一个新接口,例如MyDatabaseInterface。通用响应类将提供响应,调试消息和成功方法。

相关问题