GithubHelp home page GithubHelp logo

szogyenyid / php-builder Goto Github PK

View Code? Open in Web Editor NEW
16.0 2.0 3.0 69 KB

A PHP trait to automagically create a Builder for any class - with no dependencies

License: MIT License

PHP 94.67% Shell 5.33%
php builder design-pattern modern-php oop php8 php-traits

php-builder's Introduction

PHP Builder

A PHP trait to automagically create a Builder with fluent interface for any class.


Why PHP Builder?

Builder is a creational design pattern, which allows constructing complex objects step by step. The intent of the builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns.

As PHP does not support inner classes (like Java does), if you would like to create builders, you have to write a new class for every one you want to use a builder with, and maintain them when the base class changes. By using PHP Builder you do not need to create separate builder classes in your namespace.

PHP Builder may help preventing some bugs, as variables are only accessed once, when instantiating them with the property values already set. Alse, there is no need to write any public setters, which would make the class mutable or vulnerable. Before calling the build() method, no instance is accessible, after calling it, no properties can be changed from outside the instance (unless they are public, or have a public setter).

Instead of this, written without PHP Builder:

class User
{
    private string $name;
    private string $email;

    public function setName(string $newName): void
    {
        $this->name = $newName;
    }
    public function setEmail(string $newEmail): void
    {
        $this->email = $newEmail;
    }
}

$user = new User();
$user->setName("John Doe");
$user->setEmail("[email protected]");

You have to write this if using PHP Builder:

class User
{
    use Builder;

    private string $name;
    private string $email;
}

$user = User::builder()
    ->withName("John Doe")
    ->withEmail("[email protected]")
    ->build();

In the first case, you have to write public setters, which make your class mutable after creation. In the second case, there are no setters, and the properties are private, so there is no chance they will change after creation.

It can also increase the legibility of your code, as you get a fluent interface, and can get rid of the repetition of the variable name.

Installation

Installation is the easiest via Composer:

$ composer require szogyenyid/php-builder

or add it by hand to your composer.json file.

Upgrading

PHP Builder follows semantic versioning, which means breaking changes may occur between major releases. As the current highest version is V1, you do not need to worry about versions at this moment.

Usage

To automagically gain access to a builder, all you need to do is adding the trait to your class:

class User
{
    use Builder;
    
    //...
}

There are no rules for your class to follow to use Builder, no setters or public properties are necessary.

class User
{
    use Builder;

    private string $name;
    private string $email;
}

The above example is a 100% valid class to use Builder with.

Having this provides access to the builder, like the following:

$user = User::builder()
    ->withName("John Doe")
    ->withEmail("[email protected]")
    ->build();

All of the builder's methods will follow the names of the properties prepending with. For more legibility, you can change the first letter of the property to capital (instead of withname, you can use withName).

Possible errors

If Builder encounters any error, a BuilderException will be thrown.

If you call a builder method (except build() and reset()) that does not start with with, an exception with the following message is thrown:

Builder method names must start with "with". Invalid method name: $methodName

If a property with the corresponding name is not found, the following message will be sent with a BuilderException:

No property with name "$property" found in class $class

License

PHP Builder is licensed under MIT License.

php-builder's People

Contributors

szogyenyid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

php-builder's Issues

Add unit tests

The library is currently not covered by any unit tests, they should be added.

Invalid PHP version

Your code contains str_starts_with, which was added in PHP8. Your composer.json claims compatibility with PHP 7.4.

Either bump the PHP version in composer.json or rework the code without PHP8 language features.

PS: This might interest you: https://www.php.net/manual/en/reflectionproperty.setaccessible.php

Note: As of PHP 8.1.0, calling this method has no effect; all properties are accessible by default.

Might as well run PHP 8.1

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.