There are a few traits found in the Common package that cannot be grouped with the other guides, but are helpful nonetheless.
The Mutable trait allows for data to be read and written to from within the class layer. The data is represented as a Map<Tk, Tv> with generics that should be defined when inheriting the trait. It could also be coupled with the IteratorAggregate<Tv> and Countable interfaces for better usability.
class Foo implements IteratorAggregate<int>, Countable {
use Titon\Common\Mutable<string, int>;
}
$foo = new Foo();
$foo->set('key', 123);
$foo->get('key'); // 123The trait also supports a dot-notated key in all its key based methods.
$foo->set('parent.child', 456);
$foo->all(); // Map {'parent' => Map {'child' => 456}}The following methods are available when inheriting the trait.
| Method | Magic Method | Description |
|---|---|---|
| add(Map<Tk, Tv> $params): this | Add multiple key-value parameters. | |
| all(): Map<Tk, Tv> | Return all parameters as a map. | |
| flush(): this | Remove all parameters. | |
| get(Tk $key[, ?Tv $default]): ?Tv | __get(Tk $key): ?Tv | Return a value defined by key. If no key is found, return the default argument, or null. |
| has(Tk $key): bool | __isset(Tk $key): bool | Checks for a key in the parameters. |
| keys(): Vector<Tk> | Return the keys as a list. | |
| remove(Tk $key): this | __unset(Tk $key): void | Remove a parameter defined by key. |
| set(Tk $key, Tv $value): this | __set(Tk $key, Tv $value): void | Set a single key-value parameter. |
| values(): Vector<Tv> | Return the values as a list. |
The Stringable trait provides a very basic toString() implementation that simply returns the class name and namespace.
class Bar {
use Titon\Common\Stringable;
}
$bar = new Bar();
$bar->toString(); // Bar
(string) $bar; // Bar