PHP code example of ekvedaras / class-factory

1. Go to this page and download the library: Download ekvedaras/class-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/ */

    

ekvedaras / class-factory example snippets


use EKvedaras\ClassFactory\ClassFactory;
use EKvedaras\ClassFactory\ClosureValue;

class Account {
    public function __construct(
        public readonly int $id,
        public string $name,
        public array $orders,
        public \Closure $monitor,
    ) {
    }
}

/** @extends ClassFactory<Account> */
class AccountFactory extends ClassFactory {
    protected string $class = Account::class;
    
    protected function definition(): array
    {
        return [
            'id' => 1,
            'name' => 'John Doe',
            'orders' => [
                OrderFactory::new()->state(['id' => 1]),
                OrderFactory::new()->state(['id' => 2]),
            ],
            'monitor' => new ClosureValue(fn () => true),
        ];
    }

    public function johnSmith(): static
    {
        return $this->state([
            'id' => 2,
            'name' => 'John Smith',
        ]);
    }
}

$account = AccountFactory::new()
    ->johnSmith()                                                           // Can use predefiened states
    ->state(['name' => 'John Smitgh Jnr'])                                  // Can override factory state on the fly
    ->state(['name' => fn (array $attributes) => "{$attributes['name']}."]) // Can use closures and have access to already defined attributes
    ->after(fn (Account $account) => sort($account->orders))                // Can modify constructed object after it was created
    ->state(['monitor' => new ClosureValue(fn () => false)])                // Can set state of closure type properties using `ClosureValue` wrapper
    ->make(['id' => 3])                                                     // Can provide final modifications and return the new object

protected function newInstance(array $properties): object
{
    return Account::makeUsingProperties($properties);
}