Fixtures. AliceBundle
In the previous article, we learned about fixtures in the Symfony framework, as well as the DoctrineFixturesBundle. Let's take a look at another useful bundle for working with fixtures - AliceBundle (a wrapper around the alice component).
Some highlights:
- The ability to load data from .yml files
- Support for references
- Calling external methods
- Uses DoctrineFixturesBundle (so, after the dance, you can use shared data)
- In theory, it can be used not only for loading fixtures, but also for data (you can read from a file, recreate all the references, and then load them)
- Data generation (for example, you can generate users user0..user1)
Some obvious drawbacks:
- No ability to share references with DoctrineFixturesBundle (but you can hack it ;))
- Calling a method like <getReference('user@mail.com')> can cause unexpected problems (we'll talk about this later)
Installation:
composer require hautelook/alice-bundle
This will also install DoctrineFixturesBundle as a dependency. Register the bundles in app/AppKernel.php:
<?php
// app/AppKernel.php
public function registerBundles() { $bundles = array( // ... if (in_array($this->getEnvironment(), array('dev', 'test'))) { new DoctrineFixtureBundleDoctrineFixturesBundle(), new HautelookAliceBundleHautelookAliceBundle(), } // ... ); }
Usage
In the fixture file (for example, ..DataFixturesORMLoadData.php)
<?php
namespace AcmeDemoBundleDataFixturesORM;
use HautelookAliceBundleAliceDataFixtureLoader;
class LoadData extends DataFixtureLoader { /** * {@inheritDoc} */ protected function getFixtures() { return array( __DIR__ . '/data.yml',
); } }
In the data.yml file:
VendorBundleTestBundleEntityUser:
user0:
username: user
plainPassword: 1111
user1:
username: other_user
plainPassword: 1111
VendorBundleTestBundleEntityGroup: name: super_users users: [@user0, @user1]
This way, we load users and a group, where @user0, @user1 are references to the users described in the fixtures. You can also call methods:
VendorBundleTestBundleEntityGroup:
name: super_users
users: [<getUser('user0')>, <getUser('user1')>]
The method must be defined in the fixture loader class (in our example, LoadData). This is how you can obtain references to data loaded using DoctrineFixturesBundle. Example implementation: https://gist.github.com/harentius/798a997ae4106719448b
To retrieve references, the loader must inherit from the BaseDataFixtureLoader class (most of the code was taken from the DoctrineFixturesBundle) and use the getReference method in the yml file:
.....
users: [<getReference('user0')>, <getReference('user1')>]
That's it! For a more in-depth look, please refer to the documentation.