PHP code example of omaralalwi / php-builders

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

    

omaralalwi / php-builders example snippets




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
    {
        // Logic for sending an email
        return $this;
    }
}

namespace App\Builders;

use Omaralalwi\PhpBuilders\Traits\{Buildable, Arrayable, Objectable, Jsonable};
use App\Models\User;

class UserBuilder
{
   use Buildable,
        Arrayable,
        Objectable,
        Jsonable;
        
        // same code in first way example
}

$user = UserBuilder::build()
    ->setName('PHP Builders')
    ->setEmail('[email protected]')
    ->sendEmail();

$userAsArray = $user->toArray();
print_r($userAsArray);
/*
Output:
Array
(
    [name] => PHP Builders
    [email] => [email protected]
)
*/

$userAsObject = $user->toObject();
print_r($userAsObject);
/*
Output:
stdClass Object
(
    [name] => PHP Builders
    [email] => [email protected]
)
*/

$userAsJson = $user->toJson();
echo $userAsJson;
/*
Output:
{"name":"PHP Builders","email":"[email protected]"}
*/

namespace App\Builders;

use Omaralalwi\PhpBuilders\FluentBuilder;
use App\Models\User;

class UserBuilder extends FluentBuilder
{
   // same code in previous example, just we added execute method .
   
    public function execute(): User
    {
        // Pre-store logic (e.g., validation, preprocessing)
        return $this->store();
    }

    protected function store(): User
    {
        return User::create([
            'name' => $this->name,
            'email' => $this->email,
        ]);
    }
}

$createdUser = UserBuilder::build()
    ->setName('PHP Builders')
    ->setEmail('[email protected]')
    ->execute();
/*
$createdUser is an instance of the User model.
*/
bash
composer