Home >Backend Development >PHP Tutorial >Collection Classes in PHP
Core points
Collection classes are object-oriented alternatives to traditional array data structures. Similar to arrays, collections contain member elements, although these elements tend to be objects rather than simpler types such as strings and integers. The common features of collection classes are:- Create wrappers around object arrays. - Collections are mutable - New elements can be added and existing elements can be modified or deleted. - The sorting algorithm is unstable (this means that the order of equal elements is uncertain). - Delay instantiation can be used to save system resources.
Array Problems
Applications often have objects containing other object groups, which is a great place to use collections. For example, suppose we decide to create a bookstore system. Suppose we wrote a customer class that, among other things, also saves a list of books the customer wants to buy: ```
$customer = new Customer(1234); foreach ($customer->items as $item) { echo $item->name; }
<code> 如果最明显的方法(使用数组)是最佳方法,我不会写这篇文章。上面的例子有这些问题:- 我们破坏了封装——数组作为公共成员变量公开。- 索引以及如何遍历数组以查找特定项目存在歧义。 此外,为了确保数组可用于任何可能访问它的代码,我们必须在与客户信息同时从数据库中填充信息列表。这意味着即使我们只想打印客户的姓名,我们也必须获取所有项目信息,这会不必要地增加数据库的负载,并可能拖慢整个应用程序。我们可以通过创建一个集合类作为数组的面向对象包装器并使用延迟实例化来解决这些问题。延迟实例化是一种机制,通过这种机制,我们只在我们实际需要时才创建数组中的元素。它被称为“延迟”,因为对象自行决定何时实例化组件对象,而不是在实例化时盲目地创建它们。 **基本的集合类** 集合类需要公开允许我们添加、检索和删除项目的方法,并且拥有一个让我们知道集合大小的方法也很有帮助。因此,一个基本的类将从这里开始:``` <?php class Collection { private $items = array(); public function addItem($obj, $key = null) { } public function deleteItem($key) { } public function getItem($key) { } }</code>
$items
Array provides a location to store objects as members of the collection. addItem()
allows us to add new objects to the collection, deleteItem()
delete objects, getItem()
return objects. Using addItem()
, we add the object to the collection by putting it in the specified location of the $items
array (if no key is provided, let PHP select the next available index). If you try to add an object with an existing key, an exception should be thrown to prevent unintentional overwriting of existing information: ```
public function addItem($obj, $key = null) {
if ($key == null) {
$this->items[] = $obj;
}
else {
if (isset($this->items[$key])) {
throw new KeyHasUseException("Key $key already in use.");
}
else {
$this->items[$key] = $obj;
}
}
}
<code> 如果最明显的方法(使用数组)是最佳方法,我不会写这篇文章。上面的例子有这些问题:- 我们破坏了封装——数组作为公共成员变量公开。- 索引以及如何遍历数组以查找特定项目存在歧义。 此外,为了确保数组可用于任何可能访问它的代码,我们必须在与客户信息同时从数据库中填充信息列表。这意味着即使我们只想打印客户的姓名,我们也必须获取所有项目信息,这会不必要地增加数据库的负载,并可能拖慢整个应用程序。我们可以通过创建一个集合类作为数组的面向对象包装器并使用延迟实例化来解决这些问题。延迟实例化是一种机制,通过这种机制,我们只在我们实际需要时才创建数组中的元素。它被称为“延迟”,因为对象自行决定何时实例化组件对象,而不是在实例化时盲目地创建它们。 **基本的集合类** 集合类需要公开允许我们添加、检索和删除项目的方法,并且拥有一个让我们知道集合大小的方法也很有帮助。因此,一个基本的类将从这里开始:``` <?php class Collection { private $items = array(); public function addItem($obj, $key = null) { } public function deleteItem($key) { } public function getItem($key) { } }</code>
Because the addItem()
parameter of the $key
method is optional, we don't necessarily know the keys used by each item in the collection. It's a good idea to add a way to provide a list of keys to any external code that might require it. The key can be returned as an array: ```
public function keys() {
return array_keys($this->items);
}
<code> `deleteItem()` 和 `getItem()` 方法将键作为参数,指示哪些项目是针对删除或检索的目标。如果提供了无效的键,则应抛出异常。``` public function deleteItem($key) { if (isset($this->items[$key])) { unset($this- >items[$key]); } else { throw new KeyInvalidException("Invalid key $key."); } } public function getItem($key) { if (isset($this->items[$key])) { return $this->items[$key]; } else { throw new KeyInvalidException("Invalid key $key."); } }</code>
and because getItem()
and deleteItem()
may throw an exception if an invalid key is passed, it is also a good idea to determine if a given key exists in the set. ```
public function keyExists($key) {
return isset($this->items[$key]);
}
<code> 知道集合中有多少项目可能也有帮助。``` public function length() { return count($this->items); }</code>
This example may not be particularly interesting, but it should give you an idea of how to use this class.
Conclusion
Collections can be considered a more professional way of working listings where certain contracts are guaranteed. Collection classes are a very useful object-oriented alternative to traditional arrays and can be implemented in almost any application you may build. It provides careful management and consistent APIs for its members, which makes it easy to write code that uses the class.
(The FAQs part is omitted here because the content of this part has little to do with the main theme of the article and is too long, which will affect the pseudo-original effect. If necessary, you can make a request separately.)
>The above is the detailed content of Collection Classes in PHP. For more information, please follow other related articles on the PHP Chinese website!