PHP code example of stemble / laravel-doctrine-factory

1. Go to this page and download the library: Download stemble/laravel-doctrine-factory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

stemble / laravel-doctrine-factory example snippets


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * @implements HasFactory<UserFactory>
 */
class User
{
    use HasFactory;

    private string $name;
    private bool $admin = false;
    private Collection $posts;

    public function __construct(string $name)
    {
        $this->name  = $name;
        $this->posts = new ArrayCollection;
    }
}

use Stemble\LaravelDoctrineFactory\DoctrineFactory;

class UserFactory extends DoctrineFactory
{
    protected $model = User::class;

    public function definition(): array
    {
        return [
            'name'  => fake()->name(),
            'admin' => false,
        ];
    }

    public function admin(): static
    {
        return $this->state(['admin' => true]);
    }
}

$user  = User::factory()->create();
$users = User::factory()->count(3)->create();
$admin = User::factory()->admin()->create();

class User
{
    private string $name;
    private bool $admin = false;
    private Collection $posts;

    public function __construct(string $name)
    {
        $this->name  = $name;
        $this->posts = new ArrayCollection;
    }
}

class UserFactory extends DoctrineFactory
{
    protected $model = User::class;

    public function definition(): array
    {
        return [
            'name'  => fake()->name(),  // matched to constructor parameter
            'admin' => false,           // set via reflection after construction
        ];
    }
}

$post = Post::factory()->for(User::factory())->make();

$post->getUser();    // returns a User entity
$post->getUser_id(); // ← this doesn't exist

// `Post` has a property `User $author`
$user = User::factory()->create();
$post = Post::factory()->for($user, 'author')->create();

$post = Post::factory()->for($user)->make();

$post->getAuthor();  // returns $user      ← owning side
$user->getPosts();   // empty Collection   ← inverse side, NOT synced

class PostFactory extends DoctrineFactory
{
    protected $model = Post::class;

    public function definition(): array
    {
        return [
            'title'  => fake()->sentence(),
            'author' => User::factory(),
        ];
    }

    public function configure(): static
    {
        return $this->afterMaking(function (Post $post) {
            $post->getAuthor()->addPost($post);
        });
    }
}

class PostFactory extends DoctrineFactory
{
    protected $model = Post::class;

    // afterMaking: create child entities in-memory before flush — they'll be persisted together
    public function withComments(int $count = 3): static
    {
        return $this->afterMaking(function (Post $post) use ($count) {
            Comment::factory()->count($count)->for($post)->make();
        });
    }

    // afterCreating: needs the database-assigned ID, so it runs after flush
    public function withSlug(): static
    {
        return $this->afterCreating(function (Post $post) {
            $post->setSlug($post->getId() . '-' . str($post->getTitle())->slug());
        });
    }
}

use Doctrine\Common\Collections\ArrayCollection;

Post::factory()->create([
    'tags' => new ArrayCollection([
        Tag::factory(),         // resolved to a Tag instance
        Tag::factory()->make(), // already an instance, used as-is
    ]),
]);

class PostFactory extends DoctrineFactory
{
    public function forAuthor(User|UserFactory|array|null $author = null): static
    {
        $author ??= [];
        $author = is_array($author) ? User::factory()->make($author) : $author;

        return $this->for($author, 'author');
    }
}

// All four usages work
Post::factory()->forAuthor();
Post::factory()->forAuthor($user);
Post::factory()->forAuthor(User::factory());
Post::factory()->forAuthor(['name' => 'Alice']);

abstract class ContentFactory extends DoctrineFactory
{
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'body'  => fake()->paragraphs(3, true),
        ];
    }
}

class PostFactory extends ContentFactory
{
    protected $model = Post::class;

    public function definition(): array
    {
        return [
            ...parent::definition(),
            'author' => User::factory(),
        ];
    }
}

class PageFactory extends ContentFactory
{
    protected $model = Page::class;

    public function definition(): array
    {
        return [
            ...parent::definition(),
            'slug' => fake()->slug(),
        ];
    }
}

use LaravelDoctrine\ORM\Facades\EntityManager;

$user = User::factory()->create();
Post::factory()->for($user)->count(3)->create();

EntityManager::refresh($user);
$user->getPosts(); // now reflects the 3 new posts