PHP code example of dorofey / zf3-data-mapper

1. Go to this page and download the library: Download dorofey/zf3-data-mapper 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/ */

    

dorofey / zf3-data-mapper example snippets


class Post implements EntityInterface
{
    public $id;
    public $user;
    public $title;


    public function setId($id)
    ...
    public function getId()
    ...
}

class PostMapper extends Repository\Mapper\StandardMapper
{
    protected static $entityClass = Post::class;
    protected static $table = 'posts';

    protected static $features = [
        Repository\Mapper\Feature\Relations::class => [
            'user' => [Repository\Hydrator\HasOne::class, User::class]
        ]
    ];
}

[
    'mappers' => [
        'maps' => [
            Post::class => PostMapper::class
        ],
        'aliases' => [
            'posts' => Post::class
        ]
    ]
]

$repository = $serviceLocator->get(\Repository\Repository\RepositoryPluginManager::class);
$mapper = $repository->get(Post::class);

$singlePost = $mapper->id(10);
$allPosts   = $mapper->fetch();
$somePosts  = $mapper->fetch(['title' => 'My post title']);

$somePosts  = $mapper->fetch(function(Select $select){
    $select->where(['title' => 'My post title'])->order('cteated_at')->limit(2);
});

// In your mapper
protected static $features = [
    Repository\Mapper\Feature\SoftDelete::class => 'deleted_at' // default field is 'deleted_at'
];
....

$post = $mapper->id(10);
$mapper->delete($post);

$mapper->recover($post);

// In your mapper
protected static $features = [
    Repository\Mapper\Feature\Timestamps::class => ['created_at', 'updated_at']
];
....

// In your mapper
protected static $features = [
    Repository\Mapper\Feature\Transaction::class,
];
....

$mapper->withTransaction();

$mapper->update($post1);
$mapper->update($post2);
$mapper->insert($post3);
$mapper->delete($post4);

$mapper->commitTransaction();

// In your mapper
protected static $features = [
    Repository\Mapper\Feature\Relations::class => [
        'users'  => [HasManyThrough::class, User::class, ['post', 'user'], 'post_users'],
        'author' => [HasOne::class, User::class],
    ],
];
....

$post = $mapper->withRelation(['users', 'author])->id(10);
$post->author->name;

// In your mapper
protected static $features = [
    Repository\Mapper\Feature\SelectStrategy::class,
];
....

$post = $mapper->withStrategy(['limit' => 10, 'where' => 'author=2,age<55', 'order' => '-created_at'])->fetch();
// Or simply
$post = $mapper->fetchWithStrategy(['limit' => 10, 'where' => 'author=2,age<55']);