Code Monkey home page Code Monkey logo

class-factory's Introduction

Factory for creating objects via constructor arguments

Latest Version on Packagist Tests Total Downloads

A factory class that passes each property directly to constructor. This way your class does not need to deal with received array to create itself from and there is no reflection magic involved. This is mostly useful for creating plain classes like value objects, entities, DTOs, etc.

Installation

You can install the package via composer:

composer require --dev ekvedaras/class-factory

PhpStorm plugin

Provides autocomplete and refactoring capabillities for PhpStorm.

Usage

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

Customising class creation

If you don't want class to be created by directly passing attributes to constructor, you can override newInstance method in the factory and do change the behavior.

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

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

class-factory's People

Contributors

dependabot[bot] avatar ekvedaras avatar erikgaal avatar github-actions[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

erikgaal

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.