PHP面向对象的酒店应用

时间:2014-07-31 07:35:35

标签: php oop object

目前我正在编写一个面向对象的酒店应用程序来学习OOP。 我选择这个是因为在我的书(来自O'Reilly的PHP设计模式)中,他们编写了一家汽车租赁公司。 现在我已经完成了基本的业务逻辑,但我仍然遇到了一些问题。

在酒店课程中有以下几种方法:

//All public functions, left it hhere cause of the length
checkOut( HotelRoom $room, DateTime $from, DateTime $to )
changeRoom( HotelRoom $oldRoom, HotelRoom $newRoom, HotelCustomer $customer, DateTime $from, DateTime $to)
checkOut( HotelRoom $room, DateTime $from, DateTime $to )

因此,对于我所做的每一步(保留,更改房间或结账),我必须将HotelRoom作为参数传递。每个房间都有一个身份证和一个号码。 是否更好地实现方法addRoom(HotelRoom $room)并将所有房间存储在受保护的属性$rooms数组中,然后只传递方法的HotelRoom::$id或者有更好的方法吗?

我对OOP比较陌生,现在只想要一个好的做法。

4 个答案:

答案 0 :(得分:2)

我不会让你的Hotel课程对你提到的三个职能负责。它们是非常具体的功能,而Hotel是一个非常广泛的类。

考虑拥有RoomManagerCustomerManager类。将这些类注入Hotel类,让他们负责检索RoomCustomerRoomCustomer类应包含您概述的特定功能:

class Hotel
{
    public $roomManager;
    public $customerManager;

    public function __construct(RoomManager $rm, CustomerManager $cm)
    {
        $this->roomManager = $rm;
        $this->customerManager = $cm;
    }

    // ...
}

class RoomManager
{
    public function getRoom($id)
    {
        // find room where Room->id == $id;
        return $room;
    }

    // some other stuff may become relevant in here
}

class CustomerManager
{
    public function getCustomer($id)
    {
        // find customer where Customer->id == $id;
        return $customer;
    }

    // some other stuff may become relevant in here
}

class Room
{
    public function checkout(DateTime $from, DateTime $to)
    {
        // ...
    }
}

class Customer
{
    private $room;

    public function setRoom(Room $hr)
    {
        $this->room = $hr;
    }
}

客户端代码类似于:

// instantiate a Hotel and inject its 2 dependencies
$hotel = new Hotel(new RoomManager, new CustomerManager);

// checkout Room 3
$hotel->roomManager->getRoom(3)->checkout();

// change Customer 2's Room from Room 3 to Room 4
$newRoom = $hotel->roomManager->getRoom(4);
$hotel->customerManager->getCustomer(2)->setRoom($newRoom);

请注意您的课程的责任如何变得更加具体。 Hotel类只想管理特定组件。

答案 1 :(得分:1)

我会采取以下方式:

添加对象预订,其具有从酒店房间到客户的起点,到达和引用 然后changeRoom成为预订的方法,它只改变房间,而不是日期。 结账也成为预订的一种方式,因为提供结账日期是没有意义的。 房间在可用时保留,何时不可用,应该提供方法。 酒店拥有所有的房间,一个应该总是从酒店对象

获得房间
Hotel
getRoom($id)
getAvailableRooms($from, $to)


HotelRoom
checkIn($from, $to) - proxy to reserve($from, $to) - sets the availability
free($from, $to)

Booking
changeRoom($newRoom)
changeDates($from, $to) // this might be tricky, as it may require changing the room as well
checkOut() // sets the room from the current date to the end of the booking (in case of early checkout) as available

答案 2 :(得分:0)

你可以这样做,但是你可以拥有一个函数addRoom()而不是loadRooms(),它可以利用DataBase访问对象来加载所有房间。在预订时,您只想加载免费房间,同样适用于更换房间。您无需在checkout()中执行此操作。

答案 3 :(得分:0)

从技术上讲,这两种方法是相似的。根据干净的编码,最好传递房间对象而不是数字,因为您的代码更具可读性。任何使用你的课程的人都知道他正在和#34; room"不只是一个数字。

相关问题