Recommend this page to a friend! |
Download |
Info | Documentation | Files | Install with Composer | Download | Reputation | Support forum | Blog | Links |
Last Updated | Ratings | Unique User Downloads | Download Rankings | |||||
2024-12-13 (16 hours ago) | Not enough user ratings | Total: 20 This week: 20 | All time: 11,325 This week: 2 |
Version | License | PHP version | Categories | |||
daedalus 1.0 | GNU General Publi... | 8.1 | Algorithms, Data types, PHP 8 |
Description | Author | |
This package can manipulate lists of values. |
Daedalus is a powerful PHP library that provides advanced data structures and utilities for modern PHP applications. At its core, it offers an enhanced version of PHP's ArrayObject with additional features like type safety, event handling, immutability options, and a PSR-11 compliant dependency injection container.
The library is designed with a focus on type safety, immutability, and event-driven architecture, making it an ideal choice for building robust and maintainable applications.
License: GNU General Public License v3.0
This library is particularly useful in scenarios where you need robust array handling with type safety and change tracking. Here are some real-world use cases:
The library combines the power of PHP's ArrayObject with modern programming practices like immutability, type safety, and event-driven architecture, making it a valuable tool for building robust and maintainable applications.
composer require cmatosbc/daedalus
The Dictionary
class provides a robust key-value collection with type safety and iteration capabilities. It implements Iterator
, Countable
, and Serializable
interfaces, offering a comprehensive solution for managing key-value pairs.
use Daedalus\Dictionary;
// Create a new dictionary
$dict = new Dictionary();
// Add key-value pairs
$dict->add('name', 'John');
$dict->add('age', 30);
// Get values
$name = $dict->get('name'); // Returns 'John'
// Check if key exists
if ($dict->containsKey('age')) {
// Update value
$dict->update('age', 31);
}
// Remove a key
$dict->remove('name');
// Get all keys or values
$keys = $dict->keys(); // Returns ['age']
$values = $dict->values(); // Returns [31]
// Iterate over dictionary
foreach ($dict as $key => $value) {
echo "$key: $value\n";
}
// Clear all items
$dict->clear();
The Set
class implements a collection of unique values with standard set operations. It provides methods for union, intersection, difference, and subset operations, making it ideal for mathematical set operations and managing unique collections.
use Daedalus\Set;
// Create new sets
$set1 = new Set([1, 2, 3]);
$set2 = new Set([2, 3, 4]);
// Add and remove items
$set1->add(5); // Returns true (added)
$set1->add(1); // Returns false (already exists)
$set1->remove(1); // Returns true (removed)
$set1->remove(10); // Returns false (didn't exist)
// Check for existence
$exists = $set1->contains(2); // Returns true
// Set operations
$union = $set1->union($set2); // {2, 3, 4, 5}
$intersection = $set1->intersection($set2); // {2, 3}
$difference = $set1->difference($set2); // {5}
// Check subset relationship
$isSubset = $set1->isSubsetOf($set2); // Returns false
// Convert to array
$array = $set1->toArray(); // [2, 3, 5]
// Iterate over set
foreach ($set1 as $item) {
echo $item . "\n";
}
// Clear all items
$set1->clear();
The Set class features: - Unique value storage - Standard set operations (union, intersection, difference) - Subset checking - Object and scalar value support - Iterator implementation for foreach loops - Serialization support
The DisjointSet
class extends Set
to provide an efficient implementation of disjoint sets (union-find data structure) with path compression and union by rank optimizations. It's particularly useful for managing non-overlapping groups and determining connectivity between elements.
use Daedalus\DisjointSet;
// Create a disjoint set
$ds = new DisjointSet();
// Create individual sets
$ds->makeSet("A");
$ds->makeSet("B");
$ds->makeSet("C");
$ds->makeSet("D");
// Join sets together
$ds->union("A", "B"); // Now A and B are in the same set
$ds->union("C", "D"); // Now C and D are in the same set
$ds->union("B", "C"); // Now all elements are in the same set
// Check if elements are connected
$connected = $ds->connected("A", "D"); // Returns true
// Find the representative element of a set
$rep = $ds->find("B"); // Returns the set's representative
// Get all elements in the same set
$set = $ds->getSet("A"); // Returns ["A", "B", "C", "D"]
// Count number of disjoint sets
$count = $ds->countSets(); // Returns 1
// Clear all sets
$ds->clear();
The DisjointSet class features: - Efficient union and find operations (O(?(n)), where ? is the inverse Ackermann function) - Path compression optimization - Union by rank optimization - Set connectivity checking - Set membership queries - Multiple set management
The HashSet
class extends Set
to provide constant-time performance for basic operations. It uses hash-based storage with no guarantee of iteration order, similar to Java's HashSet.
use Daedalus\HashSet;
// Create a new HashSet with custom load factor and capacity
$set = new HashSet([], 0.75, 16);
// Add elements
$set->add("apple");
$set->add("banana");
$set->add("apple"); // Returns false (already exists)
// Bulk operations with another set
$otherSet = new HashSet(["banana", "cherry"]);
$set->addAll($otherSet); // Add all elements from otherSet
$set->removeAll($otherSet); // Remove all elements that exist in otherSet
$set->retainAll($otherSet); // Keep only elements that exist in otherSet
// Check contents
$exists = $set->contains("apple"); // Returns true
$count = $set->count(); // Get number of elements
// Convert to array (no guaranteed order)
$array = $set->toArray();
// Clear the set
$set->clear();
The TreeSet
class implements a self-balancing binary search tree (AVL tree) that maintains elements in sorted order, similar to Java's TreeSet.
use Daedalus\TreeSet;
// Create a new TreeSet
$set = new TreeSet([3, 1, 4, 1, 5]); // Duplicates are automatically removed
// Add elements (maintains order)
$set->add(2);
$set->add(6);
// Access ordered elements
$first = $set->first(); // Get smallest element (1)
$last = $set->last(); // Get largest element (6)
// Find adjacent elements
$lower = $set->lower(4); // Get largest element < 4 (3)
$higher = $set->higher(4); // Get smallest element > 4 (5)
// Check contents
$exists = $set->contains(3); // Returns true
$count = $set->count(); // Get number of elements
// Convert to sorted array
$array = $set->toArray(); // [1, 2, 3, 4, 5, 6]
// Iterate in order
foreach ($set as $element) {
echo $element . "\n";
}
// Clear the set
$set->clear();
The TreeSet class features: - Ordered element storage - Logarithmic-time operations (O(log n)) - Efficient range operations - Natural ordering for scalar types - Custom ordering via __toString for objects - AVL tree self-balancing
The Matrix
class provides a robust implementation for matrix operations in PHP, supporting various mathematical operations and transformations commonly used in linear algebra, computer graphics, and scientific computing.
use Daedalus\Matrix;
// Create a 2x2 matrix
$matrix1 = new Matrix([
[1, 2],
[3, 4]
]);
// Create another 2x2 matrix
$matrix2 = new Matrix([
[5, 6],
[7, 8]
]);
// Matrix addition
$sum = $matrix1->add($matrix2);
// Matrix multiplication
$product = $matrix1->multiply($matrix2);
// Scale matrix
$scaled = $matrix1->scale(2);
// Get determinant
$det = $matrix1->determinant();
// Create special matrices
$identity = Matrix::identity(3); // 3x3 identity matrix
$zero = Matrix::zero(2, 3); // 2x3 zero matrix
// Matrix transposition
$matrix = new Matrix([
[1, 2, 3],
[4, 5, 6]
]);
$transposed = $matrix->transpose();
// Access and modify elements
$value = $matrix->get(0, 1); // Get element at row 0, column 1
$matrix->set(1, 2, 10); // Set element at row 1, column 2
// Get matrix properties
$rows = $matrix->getRows(); // Number of rows
$cols = $matrix->getCols(); // Number of columns
A PHP library that provides an enhanced version of PHP's ArrayObject with additional features like type safety, event handling, immutability options, and a PSR-11 compliant dependency injection container.
use Daedalus\EnhancedArrayObject;
// Create a basic array object
$array = new EnhancedArrayObject([1, 2, 3]);
// Add elements
$array->offsetSet(null, 4); // Appends 4
$array[5] = 6; // Array access syntax
// Remove elements
$array->offsetUnset(0);
unset($array[1]); // Array access syntax
use Daedalus\EnhancedArrayObject;
class User {
public function __construct(public string $name) {}
}
// Create a typed array that only accepts User objects
$users = new EnhancedArrayObject([], User::class);
// This works
$users[] = new User("John");
// This throws InvalidArgumentException
$users[] = "Not a user object";
use Daedalus\EnhancedArrayObject;
$array = new EnhancedArrayObject([1, 2, 3]);
// Add event listener for modifications
$array->addEventListener('set', function($key, $value) {
echo "Element set at key $key with value $value\n";
});
$array[] = 4; // Triggers event: "Element set at key 3 with value 4"
// Remove event listener
$listener = function($key) {
echo "Element removed at key $key\n";
};
$array->addEventListener('unset', $listener);
unset($array[0]); // Triggers event
// Remove the listener when no longer needed
$array->removeEventListener('unset', $listener);
use Daedalus\EnhancedArrayObject;
$array = new EnhancedArrayObject([1, 2, 3, 4, 5]);
// Mapping
$doubled = $array->map(fn($n) => $n * 2);
// Result: [2, 4, 6, 8, 10]
// Filtering
$evens = $array->filter(fn($n) => $n % 2 === 0);
// Result: [2, 4]
// Reducing
$sum = $array->reduce(fn($carry, $n) => $carry + $n, 0);
// Result: 15
// Merging arrays
$other = new EnhancedArrayObject([6, 7, 8]);
$merged = $array->merge($other);
// Result: [1, 2, 3, 4, 5, 6, 7, 8]
// Check if empty
if ($array->isEmpty()) {
echo "Array is empty\n";
}
// Deep cloning
$clone = $array->cloneDeep();
use Daedalus\EnhancedArrayObject;
use Daedalus\ImmutableArrayObject;
// Create a mutable array
$mutable = new EnhancedArrayObject([1, 2, 3]);
// Convert to immutable
$immutable = $mutable->toImmutable();
// These will throw LogicException
$immutable[] = 4;
unset($immutable[0]);
The library includes a powerful PSR-11 compliant container with singleton management and automatic dependency injection:
use Daedalus\ContainerArrayObject;
// Create a container
$container = new ContainerArrayObject();
// 1. Basic Value Binding
$container->bind('app.name', 'My Application');
$container->bind('app.config', [
'api_key' => 'secret_key',
'cache_ttl' => 3600
]);
// 2. Class Registration with Dependencies
class Database {
public function __construct(
private string $host,
private string $username
) {}
}
class Logger {
private $logFile;
public function __construct(string $logFile = 'app.log') {
$this->logFile = $logFile;
}
}
// Register singleton with factory function
$container->singleton('database', function($container) {
return new Database('localhost', 'root');
});
// Register class for auto-instantiation
$container->bind(Logger::class, Logger::class);
// 3. Automatic Dependency Injection
class UserRepository {
public function __construct(
private Database $database,
private Logger $logger
) {}
}
// Container will automatically resolve dependencies
$container->bind(UserRepository::class, UserRepository::class);
$repo = $container->get(UserRepository::class);
// 4. Interface Binding
interface PaymentGateway {
public function process(float $amount): bool;
}
class StripeGateway implements PaymentGateway {
public function process(float $amount): bool {
return true;
}
}
// Bind interface to implementation
$container->bind(PaymentGateway::class, StripeGateway::class);
// 5. Instance Management
if ($container->has('database')) {
$db = $container->get('database');
}
// Clear cached instances
$container->clearInstances();
Key Container Features: - PSR-11 compliance - Singleton management - Automatic dependency injection - Factory function support - Interface binding - Value binding - Instance lifecycle management - Fluent interface
use Daedalus\EnhancedArrayObject;
class Product {
public function __construct(
public string $name,
public float $price
) {}
}
// Create a typed array with event handling
$products = new EnhancedArrayObject([], Product::class);
// Add event listeners
$products->addEventListener('set', function($key, $value) {
echo "Added product: {$value->name} at \${$value->price}\n";
});
// Add products
$products[] = new Product("Widget", 9.99);
$products[] = new Product("Gadget", 19.99);
// Filter expensive products
$expensive = $products->filter(fn($p) => $p->price > 10);
// Calculate total value
$total = $products->reduce(fn($sum, $p) => $sum + $p->price, 0);
The library throws the following exceptions:
Contributions are welcome! Please feel free to submit a Pull Request.
This library is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.
Files (25) |
File | Role | Description | ||
---|---|---|---|---|
.github (1 directory) | ||||
src (10 files) | ||||
tests (6 files) | ||||
composer.json | Data | Auxiliary data | ||
composer.lock | Data | Auxiliary data | ||
LICENSE | Lic. | License text | ||
phpcs.xml | Data | Auxiliary data | ||
phpunit.xml | Data | Auxiliary data | ||
README.md | Doc. | Documentation |
Files (25) | / | .github | / | workflows |
File | Role | Description |
---|---|---|
composer.yml | Data | Auxiliary data |
lint.yml | Data | Auxiliary data |
phpunit.yml | Data | Auxiliary data |
Files (25) | / | src |
File | Role | Description |
---|---|---|
ContainerArrayObject.php | Class | Class source |
Dictionary.php | Class | Class source |
DisjointSet.php | Class | Class source |
EnhancedArrayObject.php | Class | Class source |
HashSet.php | Class | Class source |
ImmutableArrayObject.php | Class | Class source |
Matrix.php | Class | Class source |
Set.php | Class | Class source |
TreeNode.php | Class | Class source |
TreeSet.php | Class | Class source |
Files (25) | / | tests |
File | Role | Description |
---|---|---|
ContainerArrayObjectTest.php | Class | Class source |
EnhancedArrayObjectTest.php | Class | Class source |
HashSetTest.php | Class | Class source |
ImmutableArrayObjectTest.php | Class | Class source |
MatrixTest.php | Class | Class source |
TreeSetTest.php | Class | Class source |
The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page. |
Install with Composer |
Version Control | Unique User Downloads | Download Rankings | |||||||||||||||
100% |
|
|
Applications that use this package |
If you know an application of this package, send a message to the author to add a link here.