PHP Builders is a sample PHP library that provides traits to implement the Builder design pattern easily in PHP applications. It allows developers to create builder classes that can construct complex objects in a fluent and readable manner.
You can install the package via Composer. Run the following command in your terminal:
composer require omaralalwi/php-builders
To create a builder class, extend the FluentBuilder
class and define your properties and methods.
namespace App\Builders;
use Omaralalwi\PhpBuilders\FluentBuilder;
class UserBuilder extends FluentBuilder
{
protected string $name;
protected string $email;
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function sendEmail(): self
{
// handle send email to user or make any action
// then return instance of self
return $this;
}
// add any another functions then call them as you need
}
You can convert the built instance to an array or an object using the toArray()
and toObject()
methods.
$userArray = UserBuilder::build()
->setName('PHP Builders')
->setEmail('[email protected]')
->sendEmail()
->toArray();
getType($userArray) // Array
$userArray['name'] // PHP Builders
$userArray['email'] // [email protected]
$userObject = UserBuilder::build()
->setName('PHP Builders')
->setEmail('[email protected]')
->sendEmail()
->toObject();
getType($userArray) // object
$userArray->name // PHP Builders
$userArray->email // [email protected]
Contributions are welcome! If you have suggestions for improvements or new features, feel free to open an issue or submit a pull request on the GitHub repository.
If you discover any security-related issues, please email creator : [email protected]
.
This project is licensed under the MIT License. See the LICENSE file for details.