kitar / laravel-dynamodb

A DynamoDB based Eloquent model and Query builder for Laravel.
MIT License
179 stars 27 forks source link

Store connection instance configuration #46

Open hschimpf opened 5 months ago

hschimpf commented 5 months ago

Store the connection configuration into the instance to be able to access it from the eloquent model through $this->getConnection()->getConfig('<index>').

In my case, as I use a Single-Table design, I want to access the connection parameters since I pass the created DynamoDB table name to it from serverless.yml:

serverless.yml

service: example

provider:
  name: aws
  ...

  environment:
    ...
    # Database Settings
    DB_CONNECTION: dynamodb
    DYNAMODB_STD_TABLE: !Ref STDTable
    ...

params:
  default:
    UUID: ${self:service}-${sls:stage}
    ...

resources:
  ...
  Resources:
    STDTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: ${param:UUID}
      AttributeDefinitions:
      ...  

config/database.php

    // ...

    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [

        // ...

        'dynamodb' => [
            'driver' => 'dynamodb',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
            'token' => env('AWS_SESSION_TOKEN'),
            'endpoint' => env('DYNAMODB_ENDPOINT'),
+           'std_table' => env('DYNAMODB_STD_TABLE'),
            'prefix' => '', // table prefix
        ],

App\Models\Base\Model.php

use Kitar\Dynamodb\Model\Model as BaseModel;

abstract class Model extends BaseModel implements Contracts\BaseModel {

    final public function getTable(): string {
        // get single-table designated table name
        return $this->table ??= $this->getConnection()->getConfig('std_table');
    }

}
kitar commented 4 months ago

Thank you for the PR! I apologize for the delay (busy days 😅), but I will definitely check it out later.