DynamoDB kết nối và sử dụng

DynamoDB kết nối và sử dụng

Như các bạn đã biết DynamoDB là 1 hệ quản trị cơ sở dữ liệu rất mạnh kiểu key ,value .Hiện tại với gói miễn phí sẽ giúp ích rất nhiều cho chúng ta , Bây giờ chúng ta sẽ demo kết nối DynamoDB đến laravel

Bước 1 : Tạo ứng dụng laravel với lệnh

composer create-project laravel/laravel la12dynamo

Bước 2 : Chúng ta cài đặt gói aws hỗ trợ php :

composer require aws/aws-sdk-php

Bước 3 : Nhập key vào hệ thống

bạn cần vào aws tạo key có quyền truy cập vào DynamoDB để nhập vào file .env

AWS_USE_PATH_STYLE_ENDPOINT=false
AWS_ACCESS_KEY_ID=xxx
AWS_SECRET_ACCESS_KEY=xxx/HUHSDPa6pwvLI
AWS_DEFAULT_REGION=ap-southeast-1
DYNAMODB_TABLE=truyenvideo
AWS_BUCKET=

Như vậy là đã xong cơ bản bây giờ bạn tạo 1 service : app\Services\DynamoDbService.php

<?php

namespace App\Services;

use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;

class DynamoDbService
{
    protected $dynamoDb;
    protected $marshaler;
    protected $table;

    public function __construct()
    {
        $this->dynamoDb = new DynamoDbClient([
            'region' => env('AWS_DEFAULT_REGION'),
            'version' => 'latest',
            'credentials' => [
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY')
            ],
        ]);

        $this->marshaler = new Marshaler();
        $this->table = env('DYNAMODB_TABLE');
    }

    // ✅ CREATE
    public function create(array $data)
    {
        $item = $this->marshaler->marshalItem($data);

        $this->dynamoDb->putItem([
            'TableName' => $this->table,
            'Item' => $item
        ]);

        return $data;
    }

    // ✅ READ
    public function get(string $post_id)
    {
        $key = $this->marshaler->marshalItem(['post_id' => $post_id]);

        $result = $this->dynamoDb->getItem([
            'TableName' => $this->table,
            'Key' => $key
        ]);

        return $result['Item'] ? $this->marshaler->unmarshalItem($result['Item']) : null;
    }

    // ✅ UPDATE (putItem là ghi đè)
    public function update(string $post_id, array $data)
    {
        $data['post_id'] = $post_id;
        return $this->create($data);
    }

    // ✅ DELETE
    public function delete(string $id)
    {
        $key = $this->marshaler->marshalItem(item: ['post_id' => $id]);

        $this->dynamoDb->deleteItem([
            'TableName' => $this->table,
            'Key' => $key
        ]);

        return true;
    }
}

Bạn lưu ý post_id này là key trong lúc bạn tạo table trong dynamoDB .Vậy là xong rất đơn giản phải không