PHP code example of musonza / dynamo-breeze

1. Go to this page and download the library: Download musonza/dynamo-breeze library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

musonza / dynamo-breeze example snippets


return [
    // 'tables' holds the configuration for all the DynamoDB tables that this package will interact with.
    'tables' => [
        // Each table has its own configuration nested under a unique logical identifier used in your application code to reference the table configuration.
        'social_media' => [
            /*
            * 'table_name' is the name of the DynamoDB table as defined in AWS.
            */
            'table_name' => 'SocialMediaTable',

            /*
            * 'partition_key' specifies the primary key attribute name of the table.
            */
            'partition_key' => 'PK',

            /*
            * 'sort_key' specifies the sort key attribute name of the table.
            * If a table doesn't have a sort key, you can omit this field.
            */
            'sort_key' => 'SK',

            /*
            * 'attributes' define the attributes and their types that the model will interact with.
            * It's used for actions like creating tables or validating input.
            * Common types: 'S' => String, 'N' => Number, 'B' => Binary.
            */
            'attributes' => [
                'PK' => 'S',
                'SK' => 'S',
                // ...
            ],

            /*
            * 'access_patterns' define various access patterns to use with the table.
            * Each access pattern has a unique name and associated settings.
            */
            'access_patterns' => [
                'FetchUserPosts' => [
                    'gsi_name' => null,
                    'key_condition_expression' => 'PK = :pk_val AND begins_with(SK, :sk_prefix_val)',
                    'expression_attribute_values' => [
                        ':pk_val' => ['S' => 'USER#<user_id>'],
                        ':sk_prefix_val' => ['S' => 'POST#'],
                    ],
                ],
                'FetchPostComments' => [
                    'gsi_name' => null,
                    'key_condition_expression' => 'PK = :pk_val AND begins_with(SK, :sk_prefix_val)',
                    'expression_attribute_values' => [
                        ':pk_val' => ['S' => 'POST#<post_id>'],
                        ':sk_prefix_val' => ['S' => 'COMMENT#'],
                    ],
                ],
                // ...
            ],
            'credentials' => 'other_account',
            // ... additional settings for the table
        ],
        
        /*
        * Additional tables, such as 'products', can have similar configurations.
        * Adapt each table configuration to match its structure and access patterns in DynamoDB.
        */
        'products' => [
            // ... configuration for the 'products' table
        ],
        // ... configurations for other tables
    ],

    /*
    * 'sdk' holds the configuration for the AWS SDK.
    */
    'credentials' => [
        'default' => [ // Default credential set
            'region' => env('DYNAMODB_REGION', 'us-west-2'),
            'version' => env('DYNAMODB_VERSION', 'latest'),
            'endpoint' => env('DYNAMODB_ENDPOINT'),
            'credentials' => [
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
            ],
        ],

        'other_account' => [ // Credentials for another AWS account
            'region' => env('DYNAMODB_OTHER_REGION', 'us-east-1'),
            'version' => env('DYNAMODB_VERSION', 'latest'),
            'endpoint' => env('DYNAMODB_ENDPOINT'),
            'credentials' => [
                'key' => env('AWS_OTHER_ACCESS_KEY_ID'),
                'secret' => env('AWS_OTHER_SECRET_ACCESS_KEY'),
            ],
        ],

        // 'another_set' => [
        //     // ...
        // ],
    ],
];

use Musonza\DynamoBreeze\Facades\DynamoBreeze;

$result = DynamoBreeze::withTableIdentifier('social_media')
    ->accessPattern('FetchUserPosts', [
        'user_id' => $userId,
    ])
    ->projectionExpression('Content, CategoryId') // specify ProjectionExpression
    ->get();

$comments = DynamoBreeze::withTableIdentifier('social_media')
    ->accessPattern('FetchPostComments', [
        'post_id' => $postId,
    ])
    ->get();

use Musonza\DynamoBreeze\Facades\DynamoBreeze;

// Perform an operation
$result = DynamoBreeze::withTableIdentifier('social_media')
    ->accessPattern('FetchUserPosts', [
        'user_id' => $userId,
    ])
    ->limit(10)
    ->exclusiveStartKey($startKey)
    ->projectionExpression('Content, CategoryId')
    ->get();

// Get the items returned from DynamoDB
$items = $result->getItems();

// Get the count of items
$count = $result->getCount();

// Access the raw AWS SDK result object
$rawResult = $result->getRawResult();

// In your config/dynamo-breeze.php configuration file

return [
    'tables' => [],
    // ... other configuration values ...

    'additional_query_mappings' => [
        'your_config_key' => 'DynamoQueryParam',
        // other custom mappings...
    ],
];

$startKey = null;
$retrievedItemsCount = 0;
$pageSize = 10; // Define your page size
$userId = 1; // The user whose posts we are fetching

do {
    /** @var DynamoBreezeResult $result */
    $result = DynamoBreeze::withTableIdentifier(self::TABLE_IDENTIFIER)
        ->accessPattern('FetchUserPosts', ['user_id' => $userId]) // Specify access pattern and relevant data
        ->limit($pageSize) // Limit the number of items fetched per request
        ->exclusiveStartKey($startKey) // Identify the starting point for the next set of results
        ->get(); // Execute the query

    $items = $result->getItems(); // Retrieve the items from the current page
    $retrievedItemsCount += $result->getCount(); // Increment the count

    // Check if there are more pages of results
    $startKey = $result->getLastEvaluatedKey();
} while ($startKey !== null);

// At this point, $retrievedItemsCount contains the total count of items retrieved
// And $items contains the items from the last fetched page

// Define the keys for the items we want to retrieve.
$tableOneKeysToGet = [
    ['PK' => 'USER#1', 'SK' => 'POST#123'],
    ['PK' => 'USER#1', 'SK' => 'POST#124'],
    ['PK' => 'USER#2', 'SK' => 'POST#123'],
    ['PK' => 'USER#3', 'SK' => 'POST#1'],
];

$tableTwoKeysToGet = [
    ['PostId' => '1', 'Timestamp' => 11111],
];

$result = DynamoBreeze::batchGet([
        'table_one_identifier' => [
            'keys' => $tableOneKeysToGet,
        ],
        'table_two_table_identifier' => [
            'keys' => $tableTwoKeysToGet,
        ],
    ]);

$result = DynamoBreeze::withTableIdentifier('social_media')
    ->accessPattern('FetchUserPosts', [
        'user_id' => $userId,
    ])
    ->projectionExpression('Content, CategoryId')
    ->get();

DynamoBreeze::withTableIdentifier('social_media')
    ->returnConsumedCapacity('TOTAL')
    ->accessPattern('FetchUserPosts', ['user_id' => $userId])
    ->get();

bash
php artisan vendor:publish --provider="Musonza\DynamoBreeze\DynamoBreezeServiceProvider"