Skip to content

Commit e051c10

Browse files
committed
Make model serializable
Close #71
1 parent 37dabf1 commit e051c10

File tree

2 files changed

+41
-7
lines changed

2 files changed

+41
-7
lines changed

src/DynamoDbModel.php

+22
Original file line numberDiff line numberDiff line change
@@ -295,4 +295,26 @@ public function setDynamoDbIndexKeys($dynamoDbIndexKeys)
295295
$this->dynamoDbIndexKeys = $dynamoDbIndexKeys;
296296
}
297297

298+
/**
299+
* Remove non-serializable properties when serializing.
300+
*
301+
* @return array
302+
*/
303+
public function __sleep()
304+
{
305+
return array_keys(
306+
array_except(get_object_vars($this), ['client', 'marshaler', 'attributeFilter'])
307+
);
308+
}
309+
310+
/**
311+
* When a model is being unserialized, check if it needs to be booted and setup DynamoDB.
312+
*
313+
* @return void
314+
*/
315+
public function __wakeup()
316+
{
317+
parent::__wakeup();
318+
$this->setupDynamoDb();
319+
}
298320
}

tests/DynamoDbModelTest.php

+19-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace BaoPham\DynamoDb\Tests;
44

5+
use Illuminate\Support\Facades\Cache;
6+
57
/**
68
* Class DynamoDbModelTest
79
*
@@ -384,17 +386,17 @@ public function testStaticMethods()
384386

385387
public function testConditionContainingIndexKeyAndNonIndexKey()
386388
{
387-
$fooItem = $this->seed([
388-
'name' => ['S' => 'Foo'],
389-
'count' => ['N' => 10],
390-
]);
391-
392-
$barItem = $this->seed([
389+
$this->seed([
393390
'name' => ['S' => 'Bar'],
394391
'count' => ['N' => 11],
395392
]);
396393

397-
$expectedItem = $this->testModel->unmarshalItem($fooItem);
394+
$item = $this->seed([
395+
'name' => ['S' => 'Foo'],
396+
'count' => ['N' => 10],
397+
]);
398+
399+
$expectedItem = $this->testModel->unmarshalItem($item);
398400

399401
$foundItems = $this->testModel
400402
->where('count', 10)
@@ -405,6 +407,16 @@ public function testConditionContainingIndexKeyAndNonIndexKey()
405407
$this->assertEquals($expectedItem, $foundItems->first()->toArray());
406408
}
407409

410+
public function testSerialize()
411+
{
412+
$item = $this->testModel->unmarshalItem($this->seed());
413+
$serializedItems = serialize($this->testModel->all());
414+
$unserializedItems = unserialize($serializedItems);
415+
416+
$this->assertEquals([$item], $unserializedItems->toArray());
417+
$this->assertInstanceOf(get_class($this->testModel), $unserializedItems->first());
418+
}
419+
408420
protected function seed($attributes = [])
409421
{
410422
$item = [

0 commit comments

Comments
 (0)