### Usage Guide Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/_MANIFEST.txt The usage guide offers practical patterns and examples for using the Dflydev Dot Access Data library effectively. ```APIDOC ## Usage Guide This document outlines practical patterns and provides real-world code examples for using the Dflydev Dot Access Data library. It is recommended for API users and application developers seeking to understand common usage scenarios and best practices. ``` -------------------------------- ### Install dflydev/dot-access-data Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/00-START-HERE.md Install the library using Composer. ```bash composer require dflydev/dot-access-data ``` -------------------------------- ### Basic Data Manipulation with Dot Notation Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/README.md Demonstrates setting, appending, getting, and checking for the existence of data using dot notation. Includes examples of default values and exception handling for missing paths. ```php use Dflydev\DotAccessData\Data; $data = new Data; $data->set('a.b.c', 'C'); $data->set('a.b.d', 'D1'); $data->append('a.b.d', 'D2'); $data->set('a.b.e', ['E0', 'E1', 'E2']); // C $data->get('a.b.c'); // ['D1', 'D2'] $data->get('a.b.d'); // ['E0', 'E1', 'E2'] $data->get('a.b.e'); // true $data->has('a.b.c'); // false $data->has('a.b.d.j'); // 'some-default-value' $data->get('some.path.that.does.not.exist', 'some-default-value'); // throws a MissingPathException because no default was given $data->get('some.path.that.does.not.exist'); ``` -------------------------------- ### Path Notation Examples Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/DataInterface.md Demonstrates the use of dot (.) and slash (/) notation for accessing and setting data within the DataInterface. Both notations are equivalent for these operations. ```php $data->get('a.b.c'); // Dot notation $data->get('a/b/c'); // Slash notation $data->set('a.b.c', 'v'); // Both are equivalent $data->set('a/b/c', 'v'); ``` -------------------------------- ### Get Data Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Illustrates retrieving values from the Data instance using dot-notation paths. Includes examples of getting nested arrays, using default values for missing paths, and handling null values. ```php $data = new Data([ 'server' => [ 'host' => 'localhost', 'port' => 8080, 'features' => ['cors', 'auth', 'logging'], 'nullValue' => null ] ]); // Get simple value $host = $data->get('server.host'); // 'localhost' // Get nested array $features = $data->get('server.features'); // ['cors', 'auth', 'logging'] // Using slash delimiter $port = $data->get('server/port'); // 8080 // Get with default (path exists) $timeout = $data->get('server.timeout', 30); // 30 // Get with default (path missing) $retries = $data->get('server.retries', 3); // 3 // Get null value with default $val = $data->get('server.nullValue', 'default'); // null (not 'default') // Without default (path missing) - throws exception try { $data->get('server.missing'); } catch (MissingPathException $e) { echo $e->getMessage(); } ``` -------------------------------- ### Handling Missing Paths with Default Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Shows how to use the `get()` method with a default value to prevent MissingPathException when a path does not exist. ```php use Dflydev\DotAccessData\Data; use Dflydev\DotAccessData\Exception\MissingPathException; $data = new Data(['server' => ['host' => 'localhost']]); // With default value (no exception) $port = $data->get('server.port', 8080); echo $port; // 8080 ``` -------------------------------- ### Demonstrate Null Handling Behavior Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/architecture.md Illustrates how the library handles null values for keys. When a key is explicitly set to null, `has()` returns true and `get()` returns null. If a path is missing and a default is provided, `get()` returns the default value only if the path is truly absent, not if it exists and is null. ```php $data->set('key', null); $data->has('key'); // true $data->get('key'); // null $data->get('key', 'default'); // null (not 'default') ``` -------------------------------- ### Behavior of get() with Default Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Illustrates that `get()` does not throw an exception when a default value is provided, even if the path is missing or the existing value is null. ```php $data = new Data(['a' => null]); // These do NOT throw: $data->get('missing', 'default'); // Returns 'default' $data->get('missing', null); // Returns null $data->get('a', 'default'); // Returns null (value exists, even though it's null) $data->get('a', 'fallback'); // Returns null (value exists) // These DO throw MissingPathException: $data->get('missing'); // No default provided $data->get('another.missing.path'); // No default provided ``` -------------------------------- ### Array Import Structure Example Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/types.md Illustrates the generic array structure supported for data import, allowing for nested arrays and mixed value types. ```php [ 'key1' => 'value1', 'key2' => [ 'nested_key' => 'nested_value', 'list' => ['item1', 'item2'] ] ] ``` -------------------------------- ### Quick Example: Data Access and Manipulation Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/INDEX.md Demonstrates initializing a Data object, accessing nested values with dot notation, using default values, checking for key existence, setting new values, appending to arrays, removing keys, and exporting the data back to an array. ```php use Dflydev\DotAccessData\Data; // Initialize with data $config = new Data([ 'database' => [ 'host' => 'localhost', 'port' => 5432, 'credentials' => [ 'user' => 'admin', 'pass' => 'secret' ] ] ]); // Access nested values $host = $config->get('database.host'); // 'localhost' $user = $config->get('database.credentials.user'); // 'admin' // With defaults $port = $config->get('api.port', 8080); // 8080 (path doesn't exist) // Check existence if ($config->has('database.port')) { $port = $config->get('database.port'); // 5432 } // Set values $config->set('cache.ttl', 3600); $config->set('cache.driver', 'redis'); // Append to arrays $config->append('features', 'auth'); $config->append('features', 'api'); // Remove keys $config->remove('database.credentials.pass'); // Export to array $array = $config->export(); ``` -------------------------------- ### Defensive Data Access: Use Defaults Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Provide default values to the 'get' method to ensure a value is always returned, even if the path does not exist, thus avoiding exceptions. ```php // No exceptions with defaults $timeout = $data->get('server.timeout', 30); $maxRetries = $data->get('api.maxRetries', 5); $debug = $data->get('app.debug', false); ``` -------------------------------- ### Type Safety in Set and Get Methods Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/architecture.md Shows the type hints for the `set` and `get` methods. While the methods expect specific types for keys, the values they handle can be of any type. ```php public function set(string $key, $value = null): void // Mixed value type public function get(string $key, $default = null) // Returns mixed ``` -------------------------------- ### get Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/DataInterface.md Retrieves the raw value for a key. If the key does not exist, an optional default value can be returned. If no default is provided and the key does not exist, an exception will be thrown. ```APIDOC ## get ### Description Get the raw value for a key. ### Method Signature `public function get(string $key, $default = null)` ### Parameters - `$key` (string) - Dot or slash-separated path to retrieve. - `$default` (mixed) - Optional default value if path does not exist. Defaults to null. ### Returns - `mixed` - The value at the path, or the default value if path doesn't exist and default was provided. ### Throws - `InvalidPathException` - If the given key is empty. - `MissingPathException` - If the given key does not exist and no default value was given. ### Mutation Free (no side effects) ``` -------------------------------- ### Get Data by Key Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Retrieves a new DataInterface instance for a specified path. The path must reference an associative array. Modifications to the returned instance do not affect the original. ```php $data = new Data([ 'database' => [ 'primary' => [ 'host' => 'db1.example.com', 'port' => 5432, 'user' => 'admin' ] ] ]); // Get a sub-data instance $db = $data->getData('database.primary'); // $db is now a DataInterface instance $host = $db->get('host'); // 'db1.example.com' $port = $db->get('port'); // 5432 // Modifications to sub-data don't affect original $db->set('port', 3306); $data->get('database.primary.port'); // Still 5432 (separate instance) ``` -------------------------------- ### get Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Retrieves a value at the specified dot-notation path. Supports an optional default value if the path does not exist. ```APIDOC ## `get` ### Signature `public function get(string $key, $default = null)` ### Description Retrieves a value at the specified dot-notation path. Supports an optional default value if the path does not exist. ### Parameters - **`$key`** (`string`) - Required - Dot or slash-separated path to retrieve. Cannot be empty. - **`$default`** (`mixed`) - Optional - Optional default value to return if the path does not exist. If not provided and path is missing, throws `MissingPathException`. ### Returns `mixed` - The value at the path, the default value if provided and path missing, or null if the value at path is null (default is returned in this case). ### Throws - `InvalidPathException` - If `$key` is an empty string or if path does not exist and no default is provided - `MissingPathException` - If path does not exist and no default value is provided ### Example ```php $data = new Data([ 'server' => [ 'host' => 'localhost', 'port' => 8080, 'features' => ['cors', 'auth', 'logging'], 'nullValue' => null ] ]); // Get simple value $host = $data->get('server.host'); // 'localhost' // Get nested array $features = $data->get('server.features'); // ['cors', 'auth', 'logging'] // Using slash delimiter $port = $data->get('server/port'); // 8080 // Get with default (path exists) $timeout = $data->get('server.timeout', 30); // 30 // Get with default (path missing) $retries = $data->get('server.retries', 3); // 3 // Get null value with default $val = $data->get('server.nullValue', 'default'); // null (not 'default') // Without default (path missing) - throws exception try { $data->get('server.missing'); } catch (MissingPathException $e) { echo $e->getMessage(); } ``` ``` -------------------------------- ### Path Delimiters with Data Class Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Demonstrates the interchangeable use of dot (.) and slash (/) as path delimiters for getting, setting, and checking data existence with the Data class. ```php $data = new Data(['a' => ['b' => ['c' => 'value']]]); $data->get('a.b.c'); // 'value' $data->get('a/b/c'); // 'value' - same result $data->set('x.y.z', 'data'); $data->set('x/y/z', 'updated'); // Overwrites the above $data->has('a.b.c'); // true $data->has('a/b/c'); // true ``` -------------------------------- ### Use Defaults to Avoid Exceptions Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Provide a default value as the second argument to the get() method to prevent exceptions when a path does not exist. This is ideal for optional settings or when a fallback value is acceptable. ```php // Get with default value (no exception thrown) $timeout = $data->get('server.timeout', 30); $retries = $data->get('api.retries', 3); $debug = $data->get('app.debug', false); // Explicitly use null as default $optional = $data->get('optional.setting', null); ``` -------------------------------- ### Use Defaults to Avoid Exceptions Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Provide a default value when getting data to prevent exceptions if the key does not exist. This is a safe way to access potentially missing data. ```php $timeout = $data->get('server.timeout', 30); // Safe ``` -------------------------------- ### Provide Defaults for Optional Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Always provide default values when getting data to prevent unexpected exceptions. This ensures your application behaves predictably even if a key is missing. ```php // Good: Provides sensible defaults $timeout = $data->get('api.timeout', 30); $maxRetries = $data->get('api.retries', 3); // Avoid: Can throw exceptions $timeout = $data->get('api.timeout'); $retries = $data->get('api.retries'); ``` -------------------------------- ### ArrayAccess Interface Implementation Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/README.md Shows how the Data object can be used like a native PHP array for getting, setting, and checking the existence of data using array access syntax. ```php // Get $data->get('name') === $data['name']; // true $data['name'] = 'Dewey'; // is equivalent to $data->set($name, 'Dewey'); isset($data['name']) === $data->has('name'); // Remove key unset($data['name']); ``` -------------------------------- ### Explicit Default Detection in get() Method Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/architecture.md Distinguishes between a missing default value and an explicitly provided `null` default using `func_num_args()`. This allows `null` to be returned as a valid value without throwing an exception. ```php public function get(string $key, $default = null) { $hasDefault = \func_num_args() > 1; // ... traversal logic ... if (!$foundKey) { if ($hasDefault) { return $default; // Return null or whatever default was passed } throw new MissingPathException($key, ...); } } ``` -------------------------------- ### Retrieve Data with Default Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Provide a default value to the get() method, which will be returned if the specified path does not exist in the data structure. This prevents errors and simplifies handling missing data. ```php $timeout = $config->get('server.timeout', 30); $retries = $config->get('api.retries', 3); // Default works even if value is null $nick = $config->get('user.nickname', 'Guest'); ``` -------------------------------- ### ArrayAccess Implementation for get() Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/architecture.md Implements the `offsetGet` method of the `ArrayAccess` interface to allow retrieving values using array-like syntax. Returns `null` for missing keys, adhering to standard PHP behavior. ```php public function offsetGet($key) { return $this->get($key, null); } ``` -------------------------------- ### Safe Path Navigation with Default Fallback Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Safely navigate nested data structures by providing a default value to the get() method. This pattern is useful for accessing potentially missing nested properties without throwing exceptions. ```php // Safe navigation with default fallback $config = new Data([ 'database' => [ 'primary' => [ 'host' => 'localhost' ] ] ]); // Try to get nested value, fall back to default $dbHost = $config->get('database.primary.host', 'localhost'); $dbPort = $config->get('database.primary.port', 5432); $dbUser = $config->get('database.primary.user', 'postgres'); ``` -------------------------------- ### Initialize Data Instance Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Demonstrates how to create a new Data instance, either empty or pre-populated with an array of data. ```php use Dflydev\DotAccessData\Data; // Empty Data instance $data = new Data(); // With initial data $data = new Data([ 'database' => [ 'host' => 'localhost', 'port' => 5432, 'credentials' => [ 'user' => 'admin', 'password' => 'secret' ] ], 'debug' => true ]); ``` -------------------------------- ### Load Configuration with Defaults Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/INDEX.md Initialize Data with a JSON configuration file and access nested values with default fallbacks. ```php $config = new Data(json_decode(file_get_contents('config.json'), true)); $dbHost = $config->get('database.host', 'localhost'); ``` -------------------------------- ### Get Nested Value With Default Value Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Provide a fallback value to the get() method to prevent exceptions when a path does not exist. The default value will be returned if the path is not found. ```php $data->get('missing.path', 'default-value') // Returns default ``` -------------------------------- ### Multi-Environment Configuration Loading Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Loads a base configuration and then merges environment-specific configuration from a JSON file, allowing for flexible environment settings. ```php $baseConfig = new Data([ 'database' => ['host' => 'localhost', 'port' => 5432], 'cache' => ['driver' => 'file'] ]); // Override with environment-specific config $env = $_ENV['APP_ENV'] ?? 'development'; $envConfig = json_decode(file_get_contents("config.$env.json"), true); $baseConfig->import($envConfig, DataInterface::MERGE); ``` -------------------------------- ### Basic Usage of Data Class Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/00-START-HERE.md Demonstrates creating a Data instance, retrieving values with and without defaults, setting new values, checking for key existence, appending to arrays, removing keys, and exporting the data. ```php use Dflydev\DotAccessData\Data; // Create instance with data $data = new Data([ 'database' => [ 'host' => 'localhost', 'port' => 5432 ] ]); // Get values echo $data->get('database.host'); // localhost echo $data->get('database.port'); // 5432 // Get with default (no exception) echo $data->get('cache.ttl', 3600); // 3600 // Set values $data->set('api.timeout', 30); // Check existence if ($data->has('database.host')) { // ... } // Append to arrays $data->append('features', 'auth'); // Remove keys $data->remove('debug'); // Export as array $array = $data->export(); ``` -------------------------------- ### Handling Missing Paths with Try-Catch Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Illustrates how to catch a MissingPathException when accessing a non-existent path without a default value, and how to retrieve the failed path. ```php use Dflydev\DotAccessData\Data; use Dflydev\DotAccessData\Exception\MissingPathException; $data = new Data(['server' => ['host' => 'localhost']]); // Without default value (throws exception) try { $timeout = $data->get('server.timeout'); } catch (MissingPathException $e) { echo "Missing: " . $e->getPath(); // Missing: server.timeout echo "Error: " . $e->getMessage(); // Error: No data exists at the given path: "server » timeout" } // Nested missing path try { $data->get('missing.nested.deeply'); } catch (MissingPathException $e) { echo "Path: " . $e->getPath(); // Path: missing.nested.deeply } ``` -------------------------------- ### Handle Invalid Paths with InvalidPathException Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Demonstrates how to catch and handle InvalidPathException when attempting to use an empty string as a path for get(), set(), or remove() operations. ```php use Dflydev\DotAccessData\Data; use Dflydev\DotAccessData\Exception\InvalidPathException; $data = new Data(); try { $data->get(''); // Invalid: empty path } catch (InvalidPathException $e) { echo "Invalid path: " . $e->getMessage(); // Output: Invalid path: Path cannot be an empty string } try { $data->set('', 'value'); } catch (InvalidPathException $e) { echo "Cannot set with empty path"; } try { $data->remove(''); } catch (InvalidPathException $e) { echo "Cannot remove with empty path"; } ``` -------------------------------- ### __construct() Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/INDEX.md Initialize a new Data object, optionally populating it with initial data from a PHP array. ```APIDOC ## __construct() ### Description Initialize a new Data object. You can provide an associative array to pre-populate the object. ### Signature `__construct(array $data = [])` ### Parameters #### Request Body - **data** (array) - An optional associative array to initialize the Data object with. ``` -------------------------------- ### Export Data When Necessary Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Export data from the Data object only when it is required, for example, when serializing it to JSON. This can improve performance by avoiding unnecessary data transformations. ```php $json = json_encode($data->export()); ``` -------------------------------- ### Instantiate and Access Exception Properties Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Demonstrates how to instantiate a MissingPathException and access its properties like the failed path and message. ```php $e = new MissingPathException('database.host', 'No data exists at the given path: "database » host"'); // From Throwable $e->getMessage(); // "No data exists at the given path: "database » host"" $e->getCode(); // 0 $e->getFile(); // File where exception was thrown // From MissingPathException $e->getPath(); // "database.host" ``` -------------------------------- ### Separate Configuration from Logic Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Load application configuration into a Data instance to easily access settings throughout your application. This promotes cleaner code and easier management of configurations. ```php // Good: Load config into Data instance $appConfig = new Data(json_decode(file_get_contents('config.json'), true)); // Then access throughout application class Database { public function __construct(Data $config) { $this->host = $config->get('database.host'); $this->port = $config->get('database.port', 5432); } } $db = new Database($appConfig); ``` -------------------------------- ### Get Nested Value Using Dot Notation Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Use dot notation to access values within nested arrays or objects. This is a more concise alternative to traditional subscripting. ```php $data->get('a.b.c') // Instead of $array['a']['b']['c'] ``` -------------------------------- ### Set Data Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Shows how to set values at specific dot-notation paths within the Data instance. Supports creating nested keys and using alternative delimiters like '/'. ```php $data = new Data(); $data->set('app.name', 'MyApp'); $data->set('app.version', '1.0.0'); $data->set('database.host', 'localhost'); $data->set('database.credentials', [ 'user' => 'admin', 'pass' => 'secret' ]); // Using slash delimiter instead of dot $data->set('api/endpoint/timeout', 30); // Set with null value $data->set('feature.beta', null); // Overwrite existing value $data->set('app.name', 'UpdatedApp'); ``` -------------------------------- ### Get Value at Path with Default Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Retrieves a value from the data structure using a dot or slash delimited path. If the path does not exist, the provided default value is returned. ```php $value = $data->get('database.host', 'localhost'); ``` -------------------------------- ### Initialize an Empty Data Instance Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Create a new instance of the Data class without any initial data. This is useful for building data structures from scratch. ```php use Dflydev\DotAccessData\Data; $data = new Data(); ``` -------------------------------- ### Get Value with Default - DataInterface Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/DataInterface.md Retrieves the value associated with a key. If the key does not exist, an optional default value is returned. Use this when a missing key should not result in an error. ```php public function get(string $key, $default = null) ``` -------------------------------- ### Configuration Management with AppConfig Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Defines a configuration class that uses Data objects to manage nested configuration settings, providing default values for missing keys. ```php class AppConfig { private $data; public function __construct(array $config = []) { $this->data = new Data($config); } public function getDatabaseHost(): string { return $this->data->get('database.host', 'localhost'); } public function getDatabasePort(): int { return $this->data->get('database.port', 5432); } public function isDebugEnabled(): bool { return $this->data->get('app.debug', false); } } $config = new AppConfig($configArray); $host = $config->getDatabaseHost(); ``` -------------------------------- ### Architecture Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/_MANIFEST.txt An in-depth explanation of the design and implementation of the Dflydev Dot Access Data library. ```APIDOC ## Architecture This document provides a deep dive into the design and implementation of the Dflydev Dot Access Data library. It is intended for library developers and those interested in the internal workings of the system. ``` -------------------------------- ### Initialize Data Instance with Initial Array Data Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Instantiate the Data class with an associative array. The library will automatically convert this into a dot-accessible structure. ```php $config = new Data([ 'app' => [ 'name' => 'MyApp', 'version' => '1.0.0', 'debug' => true ], 'database' => [ 'host' => 'localhost', 'port' => 5432, 'users' => [ 'admin' => [ 'username' => 'admin', 'password' => 'secret' ] ] ] ]); ``` -------------------------------- ### Export Data - DataInterface Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/DataInterface.md Exports the entire data structure as a raw PHP array. This method provides a way to get a snapshot of the current data for external use or serialization. ```php public function export(): array ``` -------------------------------- ### Catching Specific Exceptions in Data Access Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Illustrates how to catch and handle specific exceptions like InvalidPathException, MissingPathException, and DataException when accessing or modifying data. ```php use Dflydev\DotAccessData\Data; use Dflydev\DotAccessData\Exception\{InvalidPathException, MissingPathException, DataException}; $data = new Data(['config' => 'value']); // Invalid path (empty string) try { $data->get(''); } catch (InvalidPathException $e) { echo "Invalid path: " . $e->getMessage(); } // Missing path without default try { $data->get('missing.path'); } catch (MissingPathException $e) { echo "Missing path: " . $e->getPath(); } // Type errors (setting beyond non-array) try { $data->set('config.nested.value', 'test'); // config is string, not array } catch (DataException $e) { echo "Data error: " . $e->getMessage(); } ``` -------------------------------- ### Efficient Nested Lookups with Dot Notation Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Use dot notation for a single, efficient lookup of deeply nested data. Avoid multiple sequential 'get' calls for better performance. ```php // Efficient: Single lookup with dot notation $value = $data->get('very.deeply.nested.path.to.value'); // Less efficient: Multiple lookups $level1 = $data->get('very'); $level2 = $level1->get('deeply'); $level3 = $level2->get('nested'); // ... etc ``` -------------------------------- ### Use Structured Paths Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Employ consistent, hierarchical path naming conventions for better organization and easier data retrieval. Avoid inconsistent or ambiguous naming schemes. ```plaintext 'database.primary.host' 'database.replica.host' 'api.v1.timeout' 'api.v2.timeout' // Avoid: Inconsistent naming 'db_host' 'primary_database_hostname' 'api_v1_timeout' ``` -------------------------------- ### Get Nested Data as New Instance Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Retrieves a subset of the data structure at a specified path and returns it as a new Data instance. This is useful for operating on nested sections of the data independently. ```php $dbData = $data->getData('database'); ``` -------------------------------- ### API Reference Overview Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/_MANIFEST.txt This section provides an overview of the API reference documentation, which includes detailed information about the Data class, DataInterface, and Utility functions. ```APIDOC ## API Reference This subdirectory contains detailed documentation for the library's core components: - **Data.md**: Complete reference for the Data class. - **DataInterface.md**: Reference for the Interface contract. - **Util.md**: Reference for utility functions. ``` -------------------------------- ### Use has() for Conditional Access Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Check for the existence of a key using the `has()` method before attempting complex operations or accessing nested data. For simpler cases, using `get()` with a default value is also effective. ```php // Good: Check before complex operations if ($data->has('advanced.settings.optimization')) { optimizeForPerformance(); } // Also good: Use defaults for simpler cases $useOptimization = $data->get('advanced.settings.optimization', false); ``` -------------------------------- ### Common Data Export Patterns Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Demonstrates common patterns for exporting Data objects, such as for JSON API responses, file storage, and debugging. ```php // Export for JSON response $api_response = ['data' => $config->export()]; echo json_encode($api_response); // Export for file storage $content = json_encode($data->export(), JSON_PRETTY_PRINT); file_put_contents('config.json', $content); // Export for debugging var_dump($data->export()); print_r($data->export()) ``` -------------------------------- ### Get Data Instance for Key - DataInterface Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/DataInterface.md Retrieves a new DataInterface instance that wraps the value at a specified key. This is applicable only when the value at the key is an associative array, allowing for nested data manipulation. ```php public function getData(string $key): DataInterface ``` -------------------------------- ### API Request and Response Handling Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Demonstrates how to parse incoming request data (e.g., from $_POST) and construct a JSON response using the Data object for easy manipulation of nested structures. ```php // Working with API request data $request = new Data($_POST); $username = $request->get('user.profile.name', ''); $email = $request->get('user.contact.email', ''); // Building API response $response = new Data(); $response->set('status', 'success'); $response->set('data.id', $userId); $response->set('data.created_at', date('c')); echo json_encode($response->export()); ``` -------------------------------- ### Utility Functions Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/_MANIFEST.txt Documentation for static utility methods provided by the Util class. ```APIDOC ## Utility Functions This section details the static utility functions. ### `Util::isAssoc(array $array)` **Description**: Checks if an array is associative (i.e., has string keys). **Parameters**: - **array** (array) - Required - The array to check. **Returns**: - bool - True if the array is associative, false otherwise. ### `Util::mergeAssocArray(array $array1, array $array2)` **Description**: Merges two associative arrays recursively. **Parameters**: - **array1** (array) - Required - The first array to merge. - **array2** (array) - Required - The second array to merge. **Returns**: - array - The merged associative array. ``` -------------------------------- ### Array Access (Read, Write, Delete) Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Demonstrates how to read, write, and delete data using ArrayAccess syntax with the Data class. Supports dot notation for nested elements. ```APIDOC ## Array Access Operations ### Description This section details how to interact with the `Data` object using PHP's `ArrayAccess` interface for reading, writing, and deleting data. It highlights the support for dot notation in accessing nested data structures. ### Array Read Access ```php $data = new Data(['name' => 'John', 'email' => 'john@example.com']); // Using array syntax (dot notation paths work) $name = $data['name']; // 'John' $email = $data['email']; // 'john@example.com' $name === $data->get('name'); // true // Checking existence with isset() isset($data['name']); // true isset($data['missing']); // false ``` ### Array Write Access ```php // Using array syntax for setting (dot notation paths work) $data['name'] = 'Jane'; // Same as $data->set('name', 'Jane') $data['nested.value'] = 'test'; // Same as $data->set('nested.value', 'test') ``` ### Array Delete Access ```php // Using unset() to remove keys unset($data['name']); // Same as $data->remove('name') unset($data['nested.value']); // Same as $data->remove('nested.value') ``` ``` -------------------------------- ### Core Data Access Methods Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/00-START-HERE.md Use these methods for getting, setting, checking existence, appending, removing, and retrieving nested Data instances. The `export` method converts the Data object to a plain array. ```php $data->get('a.b.c'); // Get value (with default: get('path', 'default')) ``` ```php $data->set('a.b.c', 'value'); // Set value ``` ```php $data->has('a.b.c'); // Check exists ``` ```php $data->append('a.b.c', 'value'); // Append to array ``` ```php $data->remove('a.b.c'); // Remove key ``` ```php $data->getData('a.b'); // Get nested Data instance ``` ```php $data->export(); // Export to array ``` -------------------------------- ### Programmatic Access to Failed Path for Logging or Alternative Fetching Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/errors.md Demonstrates using a try-catch block to capture a MissingPathException, extract the failed path, and use it for logging or fetching data from an alternative source. ```php try { $data->get('database.primary.credentials.password'); } catch (MissingPathException $e) { $failedPath = $e->getPath(); // Log or report which path was accessed error_log("Access attempt to missing path: " . $failedPath); // Could use to fetch from alternative source $config = getConfigFromAlternativeSource($failedPath); } ``` -------------------------------- ### Merge Configuration Data Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/REFERENCE-SUMMARY.md Use the 'import' method with the MERGE flag to combine configuration data from different sources. This is useful for applying environment-specific overrides. ```php $config->import($envOverrides, DataInterface::MERGE); ``` -------------------------------- ### Importing Core Classes and Exceptions in PHP Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/INDEX.md Import necessary classes from the Dflydev\DotAccessData namespace and its exceptions sub-namespace. Ensure these classes are available in your project's autoloader. ```php use Dflydev\DotAccessData\Data; use Dflydev\DotAccessData\DataInterface; use Dflydev\DotAccessData\Util; // Exceptions in sub-namespace use Dflydev\DotAccessData\Exception\DataException; use Dflydev\DotAccessData\Exception\InvalidPathException; use Dflydev\DotAccessData\Exception\MissingPathException; ``` -------------------------------- ### Merge Configuration Sources Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/INDEX.md Combine multiple configuration arrays into a base Data object using a merge strategy. ```php $base = new Data($baseConfig); $base->import($envConfig, DataInterface::MERGE); ``` -------------------------------- ### Array Read Access with Data Class Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Demonstrates reading data using array syntax with the Data class. Supports dot notation for nested keys and checking existence with isset(). ```php $data = new Data(['name' => 'John', 'email' => 'john@example.com']); // Using array syntax (dot notation paths work) $name = $data['name']; // 'John' $email = $data['email']; // 'john@example.com' $name === $data->get('name'); // true // Checking existence with isset() isset($data['name']); // true isset($data['missing']); // false ``` -------------------------------- ### Use Slash or Dot Delimiters for Keys Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md The library supports both slash (`/`) and dot (`.`) delimiters for accessing and setting nested data. Both methods are equivalent for key specification. ```php // Both are equivalent $data->set('cache/redis/host', 'localhost'); $data->set('cache.redis.host', 'localhost'); $data->get('cache/redis/host') === $data->get('cache.redis.host'); // true ``` -------------------------------- ### Handling Large Data Structures Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md The library is optimized for typical configuration sizes. For very large datasets (10000+ entries), consider indexing, lazy loading, or database-backed configuration. ```php // Fine for typical config data $config = new Data(json_decode(file_get_contents('large-config.json'), true)); // For very large datasets (10000+ entries), consider: // - Indexing specific sections: $section = $data->getData('section') // - Lazy loading subsections on demand // - Database-backed configuration for very large datasets ``` -------------------------------- ### Using Slash as Path Delimiter Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/README.md Demonstrates that the library supports using a forward slash '/' as an alternative delimiter for accessing data paths, in addition to the default dot notation. ```php $data->set('a/b/c', 'd'); echo $data->get('a/b/c'); // "d" $data->get('a/b/c') === $data->get('a.b.c'); // true ``` -------------------------------- ### Array Write Access with Data Class Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Shows how to set or update data using array syntax with the Data class. Supports dot notation for nested keys, equivalent to the set() method. ```php // Using array syntax for setting (dot notation paths work) $data['name'] = 'Jane'; // Same as $data->set('name', 'Jane') $data['nested.value'] = 'test'; // Same as $data->set('nested.value', 'test') ``` -------------------------------- ### Manage Feature Flags Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/INDEX.md Use Data to store feature flag configurations and check their enabled status with a default boolean value. ```php $features = new Data($featureConfig); if ($features->get('newUI.enabled', false)) { renderNewInterface(); } ``` -------------------------------- ### Set Simple and Nested Values Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Use the `set` method to assign simple values to keys or create nested data structures. Intermediate arrays are automatically created as needed. Null and array values can also be set. ```php // Set simple values $data->set('app.name', 'NewApp'); $data->set('debug', true); // Set nested values (creates intermediate arrays) $data->set('cache.redis.host', 'redis.example.com'); $data->set('cache.redis.port', 6379); // Set with null value $data->set('feature.beta', null); // Set with array values $data->set('colors', ['red', 'green', 'blue']); $data->set('tags', ['php', 'library', 'array']); ``` -------------------------------- ### Create Nested Structures Automatically Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md The `set` method automatically creates intermediate paths and nested arrays when setting values for non-existent keys, simplifying the creation of complex data structures. ```php $data = new Data(); // Intermediate paths are created automatically $data->set('api.v2.endpoints.users', ['GET', 'POST']); $data->set('api.v2.endpoints.posts', ['GET', 'POST', 'DELETE']); // Result structure is automatically created $data->export(); // [ // 'api' => [ // 'v2' => [ // 'endpoints' => [ // 'users' => ['GET', 'POST'], // 'posts' => ['GET', 'POST', 'DELETE'] // ] // ] // ] // ] ``` -------------------------------- ### Defensive Data Access: Check Before Access Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/usage-guide.md Use the 'has' method to check for the existence of a path before attempting to access its value, preventing potential exceptions. ```php if ($data->has('feature.enabled')) { $feature = $data->get('feature.enabled'); // Safe to use $feature } ``` -------------------------------- ### Flexible Path Delimiters Normalization Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/architecture.md Normalizes various path delimiters (e.g., '/') to a single consistent delimiter ('.') for internal processing. Throws an exception for empty paths. ```php protected static function keyToPathArray(string $path): array { if (\strlen($path) === 0) { throw new InvalidPathException('Path cannot be an empty string'); } $path = \str_replace(self::DELIMITERS, '.', $path); return \explode('.', $path); } ``` -------------------------------- ### set Source: https://github.com/dflydev/dflydev-dot-access-data/blob/main/_autodocs/api-reference/Data.md Sets a value at the specified dot-notation path. Creates intermediate array keys as needed. The value can be any type, including nested arrays. ```APIDOC ## `set` ### Signature `public function set(string $key, $value = null): void` ### Description Sets a value at the specified dot-notation path. Creates intermediate array keys as needed. The value can be any type, including nested arrays. ### Parameters - **`$key`** (`string`) - Required - Dot or slash-separated path where the value should be stored. Cannot be empty. - **`$value`** (`mixed`) - Optional - The value to store. Can be any PHP type including arrays and objects. ### Returns `void` ### Throws - `InvalidPathException` - If `$key` is an empty string - `DataException` - If attempting to index into a non-array value in the path (e.g., trying to set `a.b.c` when `a.b` is already a string) ### Example ```php $data = new Data(); $data->set('app.name', 'MyApp'); $data->set('app.version', '1.0.0'); $data->set('database.host', 'localhost'); $data->set('database.credentials', [ 'user' => 'admin', 'pass' => 'secret' ]); // Using slash delimiter instead of dot $data->set('api/endpoint/timeout', 30); // Set with null value $data->set('feature.beta', null); // Overwrite existing value $data->set('app.name', 'UpdatedApp'); ``` ```