Can you provide examples or explanations of the Composite Pattern in relation to this issue?
Issue: Implementing a file system structure where both individual files and directories can be treated uniformly. Solution: The Composite Pattern can be used to represent both individual files and directories as components in a tree structure. This allows operations to be applied recursively to all components, regardless of whether they are files or directories.
interface FileSystemComponent {
public function getName(): string;
public function getSize(): int;
}
class File implements FileSystemComponent {
private $name;
private $size;
public function __construct($name, $size) {
$this->name = $name;
$this->size = $size;
}
public function getName(): string {
return $this->name;
}
public function getSize(): int {
return $this->size;
}
}
class Directory implements FileSystemComponent {
private $name;
private $children;
public function __construct($name) {
$this->name = $name;
$this->children = [];
}
public function addComponent(FileSystemComponent $component) {
$this->children[] = $component;
}
public function getName(): string {
return $this->name;
}
public function getSize(): int {
$size = 0;
foreach ($this->children as $child) {
$size += $child->getSize();
}
return $size;
}
}
// Example Usage
$file1 = new File("file1.txt", 100);
$file2 = new File("file2.txt", 200);
$dir1 = new Directory("dir1");
$dir1->addComponent($file1);
$dir1->addComponent($file2);
echo $dir1->getSize(); // Outputs: 300
Related Questions
- What are the potential pitfalls of relying solely on client-side validation for form input in PHP?
- How can PHP and AJAX be utilized to allow an admin to delete content from a DIV element for all users in a chat application?
- What are some best practices for creating dynamic links in PHP based on user-specific data?