gjerokrsteski/pimf-framework

View on GitHub
manuscript/7.-Creating-new-data-mapper-&-working-with-Entity-Manager.md

Summary

Maintainability
Test Coverage
# Creating new Data-Mapper

- we recommend you to get familiar with the Data-Mapper Pattern and PHP's PDO extension. You can read more here: [gjerokrsteski/php-identity-map](https://github.com/gjerokrsteski/php-identity-map)
- otherwise you have to go to **app/MyFirstBlog/** and create a two new subdirectories **DataMapper** and **Model** - the directories names are strict convention.
- create new model class into directory **app/MyFirstBlog/Model/** for example with name **Entry.php** and class name **MyFirstBlog\Model\Entry**
- create new data-mapper class into directory **app/MyFirstBlog/DataMapper/** for example with name **Entry.php** with class name **MyFirstBlog\DataMapper\Entry** by extending the class **Pimf\DataMapper\Base**
- create the CRUD methods you really need at the class **MyFirstBlog\DataMapper\Entry**. For better understanding how to use PDO and how to hydrate objects, read more here: [/MyFirstBlog/DataMapper/Entry.php](https://github.com/gjerokrsteski/pimf-blog/blob/master/app/MyFirstBlog/DataMapper/Entry.php)

```text
|-- app/
|   `-- MyFirstBlog/
|       |-- Controller/
|       |   '-- Blog.php
|       |-- DataMapper/
|       |   '-- Entry.php
|       |-- Model/
|       |   '-- Entry.php
```

## Working with the Entity-Manager
PIMF gives you an [Pimf\EntityManager](https://github.com/gjerokrsteski/pimf/blob/master/core/Pimf/EntityManager.php) class, based on PDO which is a
general manager for data persistence and object relational mapping. All the data-mappers who live at the **app/MyFirstBlog/DataMapper/** directory will
be loaded by the [Pimf\EntityManager](https://github.com/gjerokrsteski/pimf/blob/master/core/Pimf/EntityManager.php) only once for the whole request process.

Access the entity manager from the registry and find an blog-entry

```php
$em = $this->em;
$entry = $em->entry->find(178);
```

### Inserting a blog-article

```php
$entry = new MyFirstBlog\Model\Entry();

$entry->setTitle($title);
$entry->setContent($content);

$res = $this->em->entry->insert($entry);
```

### Updating a blog-article

```php
$em    = $this->em;
$entry = new MyFirstBlog\Model\Entry();

$entry->setTitle($title);
$entry->setContent($content);

$entry = $em->entry->reflect($entry, 178);

$res = $em->entry->update($entry);
```

### Deleting a blog-article

```php
$res = $this->em->entry->delete(178);
```