我正在使用nhibernate构建.net应用程序,用于将数据映射到实体。我仍然是面向对象编程的新手,现在我有了这个问题:
我有客户,订单,产品等实体。我可以通过nhibernate从数据库和列表客户等数据中获取对象。但是,如果我想列出客户的订单总数怎么办?这些不是客户实体的数据,也不是订单实体的数据。如何获取和列出这样的组合数据?他们应该拥有自己的数据传输对象,还是更好的方法呢?
答案 0 :(得分:0)
有一个额外的实体CustomerList
,持有 Customer
个对象。
CustomerList
将有一种方法根据订单总数对列表进行排序,这将通过访问每个memeber的订单总数并进行比较来完成。
在PHP中,我会做类似的事情(这只是一个例子,在实际代码中可能还有其他事情你需要考虑)。
<?php
/**
* Describe a single customer object
*/
class Customer {
/** @var Order[] List of orders */
private $orders = array();
/**
* Add an order to the order list.
*
* @param Order $order
*/
public function addOrder(Order $order) {
if (!in_array($order, $this->orders, true)) {
$this->orders[] = $order;
}
}
/**
* Get an order by numeric index.
*
* @param int $index
*
* @return Order
*/
public function getOrder($index) {
return $this->orders[$index];
}
/**
* Get total number of orders for customer.
*
* @return int
*/
public function getOrdersTotal() {
return count($this->orders);
}
}
/**
* Describe a single order.
* I didn't include any information here because it's not relevant.
*/
class Order {
}
/**
* Describe a list of customers.
*/
class CustomerList {
/** @var Customer[] List of customers */
private $customers;
/**
* Add a customer to the list
*
* @param Customer $customer
*/
public function addCustomer(Customer $customer) {
$this->customers[] = $customer;
}
/**
* The sorting function.
* Compare the orders total and return 1/0/-1 accordingly.
*
* @param Customer $a
* @param Customer $b
*
* @return int
*/
public function sort($a, $b) {
if ($a->getOrdersTotal() === $b->getOrdersTotal()) {
return 0;
}
return ($a->getOrdersTotal() > $b->getOrdersTotal()) ? 1 : -1;
}
/**
* Call the sorting function on the customer list
*/
public function sortCustomers() {
usort($this->customers, array($this, "sort"));
}
/**
* Return the full customer array.
*
* @return Customer[]
*/
public function getCustomers() {
return $this->customers;
}
}
//Instantiation
$cList = new CustomerList();
$customer1 = new Customer();
$customer2 = new Customer();
$customer3 = new Customer();
$order1 = new Order();
$order2 = new Order();
$order3 = new Order();
$order4 = new Order();
$order5 = new Order();
$order6 = new Order();
$customer1->addOrder($order1);
$customer1->addOrder($order2);
$customer2->addOrder($order3);
$customer3->addOrder($order4);
$customer3->addOrder($order5);
$customer3->addOrder($order6);
$cList->addCustomer($customer1);
$cList->addCustomer($customer2);
$cList->addCustomer($customer3);
//List customers before sorting
var_dump($cList->getCustomers());
$cList->sortCustomers();
//List customers after sorting
var_dump($cList->getCustomers());