Skip to content
This repository has been archived by the owner on Nov 17, 2020. It is now read-only.

Commit

Permalink
Allow to use callables as values in AbstractFixture
Browse files Browse the repository at this point in the history
  • Loading branch information
Orbitaleio committed Mar 8, 2016
1 parent 193fee8 commit 2affc30
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
6 changes: 6 additions & 0 deletions AbstractFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ private function fixtureObject($datas)
$class = $this->entityClass;
$obj = new $class;
foreach ($datas as $field => $value) {

// If the value is a callable we execute it and inject the fixture object and the manager.
if (is_callable($value, true)) {
$value = $value($this, $this->manager);
}

if ($this->propertyAccessor) {
$this->propertyAccessor->setValue($obj, $field, $value);
} else {
Expand Down
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,70 @@ class PostFixtures extends AbstractFixture

```

### Using a callable to get a reference

When you have self-referencing relationships, you may need a reference of an object that may have already been persisted.

For this, first, you should set the `flushEveryXIterations` option to `1` (view below) to allow flushing on every iteration.

And next, you can set a `callable` element as the value of your object so you can retrieve manually the reference from the
injected `AbstractFixture` object as first argument.

The `ObjectManager` is also injected as second argument in case you need to do some specific requests or query through another
table.

Example here:

```php
<?php

namespace AppBundle\DataFixtures\ORM;

use Orbitale\Component\DoctrineTools\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

class PostFixtures extends AbstractFixture
{

public function getEntityClass() {
return 'AppBundle\Entity\Post';
}

/**
* With this, we can retrieve a Post reference with this method:
* $this->getReference('posts-1');
* where '1' is the post id.
*/
public function getReferencePrefix() {
return 'posts-';
}

/**
* Set this to 1 so the first post is always persisted before the next one.
*/
public function flushOnEveryXIterations() {
return 1;
}

public function getObjects() {
return [
['id' => 1, 'title' => 'First post', 'parent' => null],
[
'id' => 2,
'title' => 'Second post',
'parent' => function(AbstractFixture $fixture, ObjectManager $manager) {
return $fixture->getReference('posts-1');
},
],
];
}

}

```

This allows perfect synchronicity when dealing with self-referencing relations.

### Methods of the `AbstractFixture` class that can be overriden:

* `getOrder()` to change the order in which the fixtures will be loaded.
Expand Down

0 comments on commit 2affc30

Please sign in to comment.