Skip to content

7. Creating new data mapper & working with Entity Manager

gjerokrsteski edited this page Mar 17, 2014 · 7 revisions
  • we recommend you to get familiar with the Data-Mapper Pattern and PHP's PDO extension. You can read more here: 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: https://github.com/gjerokrsteski/pimf-blog/blob/master/app/MyFirstBlog/DataMapper/Entry.php
|-- app/
|   `-- MyFirstBlog/
|       |-- Controller/
|       |   '-- Blog.php
|       |-- DataMapper/
|       |   '-- Entry.php
|       |-- Model/
|       |   '-- Entry.php

Using the Entity Manager

PIMF gives you an Pimf\EntityManager 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 only once for the whole request process.

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

$em = Pimf\Registry::get('em');
$entry = $em->entry->find(178);

Inserting a blog-article

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

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

$res = Pimf\Registry::get('em')->entry->insert($entry);

Updating a blog-article

$em    = Pimf\Registry::get('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

$res = Pimf\Registry::get('em')->entry->delete(178);