Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Alice Generator Bundle Laravel Package

trappar/alice-generator-bundle

A Symfony bundle that generates Alice fixtures from your Doctrine entities and existing database data, making it faster to create realistic test data and seed development environments.

View on GitHub
Deep Wiki
Context7

Getting Started

This is a dev-only tool: it reads Doctrine-managed entities out of an existing database and emits nelmio/alice YAML. It is not a fixture loader and has no runtime role. The common first use is "I have a dev database full of realistic data, give me a YAML fixture file I can commit and reuse in tests."

composer require --dev trappar/alice-generator-bundle

The package is from 2018, so pin your nelmio/alice constraint to whatever the bundle's composer.json expects (2.x/3.x era) and expect resolution failures on PHP 8 / Symfony 5+. Register the bundle manually — there is no Flex recipe:

// Symfony 3/4 AppKernel.php
new Trappar\AliceGeneratorBundle\TrapparAliceGeneratorBundle(),

Where to look first. The README is thin, so read these three things in the package source, in order:

  1. DependencyInjection/Configuration.php — the only reliable list of config keys (fixtures_path, YAML dumper options, etc.).
  2. Command/ — confirm the actual command name (typically trappar:alice:generate, but verify with bin/console list for your installed tag).
  3. Fixture/FixtureInterface.php and Generator/FixtureGenerator.php — the contract and the object-walking logic.

First use case. Create a fixture class that returns the entities you want dumped:

use Trappar\AliceGeneratorBundle\Fixture\FixtureInterface;

class ProductFixture implements FixtureInterface
{
    private $products;

    public function __construct(ProductRepository $products)
    {
        $this->products = $products;
    }

    public function getContext()
    {
        // Return the objects to walk. Keep it bounded.
        return $this->products->createQueryBuilder('p')
            ->setMaxResults(50)
            ->getQuery()
            ->getResult();
    }

    public function getOrder()
    {
        return 0;
    }
}

Configure the output directory, then run the generator and inspect the YAML:

# config.yml
trappar_alice_generator:
    fixtures_path: "%kernel.root_dir%/../app/Resources/fixtures"
bin/console trappar:alice:generate   # confirm name with `bin/console list`

Implementation Patterns

Snapshot bounded subsets, not the whole schema. The generator walks object graphs; findAll() on a large table is the fastest way to exhaust memory. Always cap with setMaxResults, filter to a representative slice, or run against a freshly seeded dev database.

One fixture class per aggregate, ordered with getOrder(). Split by domain (UserFixture, ProductFixture, OrderFixture) and assign increasing orders so users exist before orders. This mirrors doctrine/data-fixtures ordering and keeps the emitted YAML readable.

References need object identity. Alice's @user_1 syntax is emitted when the generator sees the same managed instance referenced from two places. Load related objects from the same EntityManager without calling clear() in between, and make sure both sides are actually managed (not detached DTOs or newly new'd objects).

// Both sides stay in the identity map -> generator emits @order_1 style refs
$orders = $orderRepo->findBy(['status' => 'shipped'], 20);

Constraints are the primary extension point. Built-in constraints let you drop properties by class or property name; custom ones implement the constraint interface and are registered as tagged services (check Resources/config/services.yml for the exact tag). Use them to strip fields that should never be in fixtures:

// Conceptual shape — confirm interface/method names in Constraint/
class StripSensitiveConstraint implements ConstraintInterface
{
    public function accept($value, ConstraintContext $context)
    {
        return !in_array($context->getPropertyName(), ['id', 'password', 'apiToken'], true);
    }
}

Post-process for anonymization. Even with constraints, real dev data contains real emails and names. Either add a constraint that rewrites values, or pipe the generated YAML through a small normalizer to replace values with faker calls (<email()>, <name()>) so fixtures stay valid under Alice's parser.

Generate programmatically for CI. Rather than shelling out to the command, inject FixtureGenerator into your own console command or test and call it directly. This is useful for nightly "refresh fixtures from staging snapshot" jobs and avoids depending on the command's fragile option set.

Pair with a loader. This bundle only writes YAML. To actually load it in tests, use hautelook/alice-bundle / theofidry/alice-data-fixtures on the same legacy Symfony version, or nelmio/alice directly:

$objects = (new \Nelmio\Alice\Loader\NativeLoader())
    ->loadFile('app/Resources/fixtures/products.yml')
    ->getObjects();

Keep a dedicated dev data source. Point the generator at a scrubbed snapshot database, not something that requires production credentials. Wrap the generation step in your onboarding docs so new developers can refresh fixtures in one command.

Gotchas and Tips

  • This is effectively unmaintained. Last release April 2018, zero dependents, no PHP 8 / Symfony 5+ support. Treat it as a one-off migration tool: run it once, commit the YAML, then drop the dependency. Do not put it in a long-lived CI pipeline.
  • Dependency conflicts are likely. The bundle pulls an old nelmio/alice and old Symfony components. If you cannot install it, pin the conflicting packages or run it inside a throwaway container/Vagrant box rather than fighting Composer.
  • Doctrine proxies confuse class-based constraints. Lazy proxies have a different get_class() than the real entity. Initialize associations before generation (or filter proxies by their parent class) if constraints silently fail to match.
  • Bidirectional associations cause duplication and loops. User::$orders and Order::$user both get emitted, producing doubled data and potential recursion. Drop one side with a constraint — usually the inverse side — and reload with the owning side intact.
  • Auto-increment IDs break portability. IDs from your dev DB will collide on load. Strip id via a constraint and let the loader assign primary keys; emit references instead of hard-coded ID values.
  • Binary/blob fields corrupt YAML. BLOB/JSON columns containing raw bytes will produce unparseable output or giant base64 lines. Always exclude them.
  • DateTimes need a stable format. The YAML dumper emits a string representation; whether Alice can reparse it depends on the format and timezone. Verify a round-trip (generate → load) before committing fixtures, and normalize to ISO-8601 in a constraint if necessary.
  • Unique indexes bite on reload. Generated values may repeat across fixture files. Convert sensitive/scalar fields to Alice <faker> or <sequence> expressions in post-processing.
  • Empty output usually means an empty context. If the command produces [], your getContext() returned detached objects or an empty repository result. Dump the array length before generation to isolate.
  • Command name and options drift between tags. Since there is no stable docs page, always run bin/console list trappar and bin/console help <command> against the exact version you installed rather than trusting a blog post.
  • Output paths are relative to %kernel.root_dir%. A typo in fixtures_path fails silently or writes to an unexpected directory. Use an absolute path in CI and check file permissions on the target directory.
  • Big fixture files get repetitive. The generator does not emit YAML anchors, so a 2,000-object dump is large and slow to diff. Generate per-aggregate files rather than one monolith, and commit them separately.
  • Debug via the object set, not the YAML. The fastest way to diagnose bad output is to intercept the objects before the writer (custom generator service, var_dump of getContext(), or an Xdebug breakpoint in FixtureGenerator), not to reverse-engineer a 500-line YAML file.
  • Migration advice. For new projects on modern Symfony, skip this package and write a small custom command that iterates selected entities and emits Alice YAML yourself — it's ~100 lines, you control the constraints, and you stay compatible with current nelmio/alice / theofidry/alice-data-fixtures.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource