【问题标题】:Return Objects (PHP Best Practices)返回对象(PHP 最佳实践)
【发布时间】:2016-05-24 23:10:47
【问题描述】:

在编写 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 的正常路线。

【问题讨论】:

  • @ScottWeldon ,注意;仍然在这里学习不同的部分。谢谢
  • @joegrom5 有多个问题与 Programmers 重复:我建议在那里搜索一些好的信息。
  • @ScottWeldon 在引用其他网站时,指出cross-posting is frowned upon 通常会有所帮助
  • @gnat 好点,谢谢。我记下了这一点,这样我以后就不会忘记这样做了。

标签: php oop


【解决方案1】:

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

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 等时,它们都将实现您的响应接口,因此您的公共 getter 将可用,例如:

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

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

【讨论】:

    猜你喜欢
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多