Skip to content

Commit

Permalink
Add doc
Browse files Browse the repository at this point in the history
  • Loading branch information
bakura10 committed May 16, 2014
1 parent 730989a commit b2d03a9
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions docs/07. Cookbook.md
Expand Up @@ -304,6 +304,70 @@ change the cache option to use something like APC:
]
```

### Optimized COUNT when using paginator

*Only from Doctrine ORM 2.5*

This is a very important optimization and should not be forget if you use the paginator, otherwise you may run
into a lot of problems.

Let's assume the following code:

```php
class Conversation
{
/**
* @ORM\OneToMany(targetEntity="Message", mappedBy="conversation")
* @REST\Association(routable=true)
*/
protected $messages;
}
```

```php
class Message
{
/**
* @ORM\ManyToOne(targetEntity="Conversation", inversedBy="messages")
*/
protected $conversation;
}
```

If you have a properly configured router, this code allows to access to all messages of a given conversation using
the following endpoint: GET `/conversations/:id/messages`. By doing this, you will receive a Selectable into the
list controller defined in the Message mapping.

However, you may have a lot of messages, so to avoid running out of memory, the solution is usually to use a paginator:

```php
class MessageListController extends AbstractRestfulController
{
public function get(Selectable $messages)
{
$paginator = $this->paginatorWrapper($messages);
$paginator->setCurrentPageNumber($this->params()->fromQuery('page', 1));

return $this->resourceModel($paginator);
}
}
```

The problem with this code is that the paginator needs to do a count over the collection. However, internally Doctrine
will first load into memory ALL the collections, defeating the whole purpose of using a paginator. To force Doctrine
to make an optimized count, you need to modify the association mapping and set its fetch mode to EXTRA_LAZY:

```php
class Conversation
{
/**
* @ORM\OneToMany(targetEntity="Message", mappedBy="conversation", fetch="EXTRA_LAZY")
* @REST\Association(routable=true)
*/
protected $messages;
}
```

### Using cache

We need to wait Doctrine 2.5 for that. But I promise, that will be truly awesome.
Expand Down

0 comments on commit b2d03a9

Please sign in to comment.