In Table Generator, collections are used to manage multiple instances of a particular table component. Collections ensure that elements that can appear multiple times within a table structure are handled efficiently and consistently.
Purpose of Collections
Collections act as containers for multiple instances of a specific component, such as table rows (Tr
), table bodies (Tbody
), or columns (Col
). They provide methods for adding, retrieving, and manipulating these elements.
Available Collections
The following collections are available in Table Generator:
Collection Name | Description |
---|---|
TrCollection |
Manages multiple Tr instances within a Tbody or Thead . |
TbodyCollection |
Manages multiple Tbody instances within a Table . |
CellCollection |
Manages multiple Td or Th instances within a Tr . |
ColCollection |
Manages multiple Col instances within a ColGroup . |
ColGroupCollection |
Manages multiple ColGroup instances within a Table . |
Implementing CollectionInterface
All collections implement the CollectionInterface
, which provides a consistent API for interacting with grouped elements. The interface includes the following methods:
interface CollectionInterface {
public function toArray(): array;
public function isEmpty(): bool;
public function count(): int;
public function sort(callable $callback): static;
public function clear(): int|bool;
}
Working with Collections
Each collection has specific methods related to its elements but follows a similar pattern:
Creating a collection instance
$trCollection = new TrCollection();
Adding an Element to the end
$trCollection->append(new Tr()); // insert at end
Adding an Element to the beginning
$trCollection->prepend(new Tr()); // insert at beginning
Adding an Element to specific position
$trCollection->insertAt(3, new Tr()); // insert at index 3
Retrieving an Element
$tr = $trCollection->get(0); // Retrieves the first Tr element
Checking for an Element
$exists = $trCollection->has($tr); // Returns true if the element exists
Removing an Element
$trCollection->remove($tr); // Removes the element if it exists
Get the position of an Element
$trCollection->indexOf($tr); // Get the index of the element
Get the first Element
$trCollection->first(); // Get the first element in the collection
Get the position of an Element
$trCollection->last(); // Get the last element in the collection
Sorting Elements
$trCollection->sort(function(Tr $a, Tr $b) {
return strcmp(
$a->getAttributes()->get('class'),
$b->getAttributes()->get('class')
);
});
These collections make it easy to manage table elements dynamically, allowing flexibility while maintaining structure and consistency.