我來自程序化編程的世界,彙編程序是我的第一語言,PL/1和Cobol是我學習我大部分(壞)習慣的語言。舊的程序員程序員的OOP結構
這是我第一篇文章,所以請接受我的道歉,如果我沒有做到100%正確。
我正在改寫我們的前端和後端系統,從程序化的PHP到OOP,我真的不知道要使用什麼結構。
在舊系統中,我們有許多腳本,其中包括使用函數的xxx.inc.php,而xxx.inc.php又包含其他xxx.inc.php,如db.inc.php, api_pj.inc.php等
試圖做到這一點,我爲每個類創建一個文件並自動加載它們,但我無法理解如何處理常見類(數據庫,連接到外部api的等)。測試時,我使用繼承,它工作正常,但感覺很奇怪。我無法真正看到客戶類是數據庫類的孩子。 另外我不明白什麼需要定義而不是。是否應該定義類中的所有變量?
下面的示例不起作用,因爲數據庫連接不適用於Customer類。當「類客戶擴展數據庫」,而不是一切正常,但我想有一個更正確的方式做到這一點?
編輯亞歷安德烈
the_example_page.php
// autoloader
spl_autoload_register(function ($class) {
require_once 'classes/' . $class . '.class.php';
});
// data for testing
$customer_id = '12090';
$order_id = '31480';
// db
$db = new DB();
$db_conn = $db->db_connect();
// get customer name data and print it:
$customer = new Customer($db_conn);
$customer_data = $customer->get_customer_info($customer_id);
print $customer_data['name'];
// get order date and print it:
$order = new Order($db_conn);
$order_data = $order->get_order_info($order_id);
print $order_data['date'];
DB.class.php
class DB
{
public function __construct() {}
public function db_connect()
{
static $db_conn;
if(!$db_conn)
{
$db_conn = pg_connect("dbname=database user=user password=PaSsWoRd");
}
return $db_conn;
}
public function db_exec($sql)
{
if(!$sql) return;
$db_conn = $this->db_connect();
$result = @pg_exec($db_conn,$sql);
if(!$result)
{
return;
}
$ret[result] = $result;
return $ret;
}
public function db_getrow(&$a)
{
# a bunch of stuff in real function, but here only a plain fetch_array as example
$ret = pg_fetch_array($a);
return $ret;
}
}
Customer.class.php答覆後下方代碼
class Customer
private $conn;
{
public function __construct($db)
{
$this->conn=$db;
}
public function get_customer_info($customer_id)
{
return $this->conn->db_getrow($this->conn->db_exec("SELECT * FROM customer WHERE customerid = $customer_id;"));
}
public function get_all_customers($status)
{
return $this->conn->db_exec("SELECT * FROM customer WHERE status = $status;");
}
}
Order.class.php
class Order
{
private $conn;
{
public function __construct($db)
{
$this->conn=$db;
}
public function get_order_info($order_id)
{
return $this->conn->db_getrow($this->conn->db_exec("SELECT * FROM order WHERE orderid = $order_id;"));
}
public function get_all_orders($status)
{
return $this->conn->db_exec("SELECT * FROM order WHERE status = $status;");
}
}
的確是一個CUS tomer *不是*數據庫,所以它不應該繼承它。研究***依賴注入***。從看起來像'$ db = new Database('foo','bar')的消費者一方; $ cust = new Customer($ db);'。更好的是:'$ manager = new CustomerManager($ db); $ cust = $ manager-> get(42);'。看看*庫模式* – deceze