Last active
July 24, 2020 09:56
-
-
Save janpecha/00647d93efdda08076b105e6ee21a64e to your computer and use it in GitHub Desktop.
Lean Mapper entity testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// LeanMapper 3.4.2 | |
require __DIR__ . '/vendor/autoload.php'; | |
class AppMapper extends \LeanMapper\DefaultMapper | |
{ | |
protected $defaultEntityNamespace = ''; | |
} | |
/** | |
* @property int $id | |
* @property string $name | |
* @property Book[] $books m:belongsToMany | |
*/ | |
class Author extends \LeanMapper\Entity | |
{ | |
} | |
/** | |
* @property int $id | |
* @property Author $author m:hasOne | |
* @property string $name | |
*/ | |
class Book extends \LeanMapper\Entity | |
{ | |
} | |
$connection = new LeanMapper\Connection([ | |
'driver' => 'sqlite3', | |
'database' => ':memory:', | |
'lazy' => TRUE, | |
]); | |
$mapper = new AppMapper; | |
$entityFactory = new LeanMapper\DefaultEntityFactory; | |
// WRONG WAY | |
// $author = new Author; | |
// $author->name = 'John Doe'; | |
// $author->makeAlive($entityFactory, $connection, $mapper); | |
// $author->attach(1); | |
// $author->books = []; // error => Cannot write to read-only property 'books' in entity Author | |
// RIGHT WAY | |
$authors = LeanMapper\Result::createInstance([ | |
[ | |
'id' => 1, | |
'name' => 'John Doe', | |
], | |
], 'author', $connection, $mapper); | |
$books = LeanMapper\Result::createInstance([ | |
[ | |
'id' => 1, | |
'author_id' => 1, | |
'name' => 'Book A', | |
], | |
[ | |
'id' => 2, | |
'author_id' => 2, | |
'name' => 'Book B', | |
], | |
[ | |
'id' => 3, | |
'author_id' => 1, | |
'name' => 'Book C', | |
], | |
], 'book', $connection, $mapper); | |
$authors->setReferencingResult($books, 'book', 'author_id'); | |
$books->setReferencedResult($authors, 'author', 'author_id'); | |
$author = new Author($authors->getRow(1)); | |
$author->makeAlive($entityFactory); | |
// prints: 'Book A', 'Book C' | |
foreach ($author->books as $book) { | |
var_dump($book->name); | |
var_dump($book->author->name); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment