返回对象(PHP 最佳实践)



在编写 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; }

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

我在此实践中的主要目标是确保我在处理方法返回数据的方式上保持一致。

注意:怜悯。这是我在这里的第一个问题。:)我已经慢慢地自学了,从几年前涉足html到转向程序化php,最后进入OOP。

这对我来说似乎是一个完全合理的方法。

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

然后你知道,每当你的对象返回一个JsqlResponse、一个TimeResponse、一个MemberResponse等时,它们都应该实现你的响应接口,因此你的公共getter将可用,例如:

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

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

最新更新