[英]Return Objects (PHP Best Practices)
在編寫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
而言,可以使響應類實現Response 接口 ,然后您將知道所有類型的響應類都將遵循相同的規則,因此可以在整個過程中安全地使用它你的申請:
interface MyResponseInterface
{
public function getResponse();
public function getDebugMessage();
public function getSuccess();
public function getMysqliConnection();
}
class JsqlResponse implements MyResponseInterface
{
// ...
}
然后,您知道只要您的對象返回JsqlResponse
, TimeResponse
, MemberResponse
等,它們都將實現您的響應接口,因此您的公共獲取器將可用,例如:
/** @var MyResponseInterface $return */
$return = $db->connect(...);
if($return->getSuccess()) {
echo $return->getResponse();
} else {
echo $return->getDebugMessage();
}
注意:在我可能返回的各種響應的示例中,我想(假設),Time和Member可能不需要MySQL連接,因此也許您可以從MyResponseInterface
忽略它,並為數據庫連接創建一個新接口,例如MyDatabaseInterface
。 通用響應類將提供響應,調試消息和成功方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.