我創造了一些課,但我不知道這種做法是非常堅實的。PHP類設計
我存儲產品的產品類中是這樣的:
class Product {
private $id;
private $partNumber;
private $description;
private $stock;
/**
* Product constructor.
* @param $id
* @param $partNumber
* @param $description
*/
public function __construct($id, $partNumber, $description){
include_once(APPPATH.'controllers/Core_Stock_Controller_Test.php');
$this->id = $id;
$this->partNumber = $partNumber;
$this->description = $description;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getPartNumber()
{
return $this->partNumber;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @return Stock
*/
public function getStock(){
if($this->stock == null){
$stockController = new Core_Stock_Controller_Test();
$this->stock = $stockController->getStockFromProduct($this);
}
return $this->stock;
}
}
但我對此有些疑問了,我有一個腳本在我的構造函數:include_once(APPPATH.'controllers/Core_Stock_Controller_Test.php');
因爲我需要這個在getStock方法。有沒有更好的方法來做到這一點?
我加載時調用該方法的股票,因爲我不每次都需要它(所以我覺得它的速度更快這種方式,因爲有時我需要超過200個產品)。在課堂上創建另一個對象是否正確?
股票控制器:
class Core_Stock_Controller_Test{
public function __construct() {
$CI =& get_instance();
$CI->load->model('Core_Stock_Model');
}
private function getInstance(){
return get_instance();
}
public function getStockFromProduct(Product $product){
$result = $this->getInstance()->Core_Stock_Model->getStockForAllLocationPerPartId($product->getId());
$locations = array();
$totalStock = 0;
foreach($result as $res){
$totalStock = $res["total"];
$location = new Location($res["location_id"], $res["cd_mag"], $res["cd_location"], $res["cd_loc_type"], $res["stock"]);
array_push($locations, $location);
}
return new Stock($locations, $totalStock);
}
}
可正常工作。但是,這段代碼是否設計正確?因爲我的一些話是說這種方法不是它需要的方式。
這個問題最有可能被關閉,因爲它是基於意見。在我看來,不,這不是正確的方法。您將一個類作爲依賴項耦合到另一個類。相反,你應該使用自動加載('include()'調用方式不太靈活)並且構建一個接口類並將其作爲依賴項傳入。查找「依賴注入」和接口。 –
你真的應該考慮閱讀作曲家 –
這個問題是比較適合[代碼審查(http://codereview.stackexchange.com/) –