Skip to content

Commit d9c7312

Browse files
authored
Merge pull request #1 from omaralalwi/feat/ability-to-return-json
Feat / add ability to json cast
2 parents cf8869a + a1f0480 commit d9c7312

File tree

4 files changed

+173
-38
lines changed

4 files changed

+173
-38
lines changed

README.md

Lines changed: 150 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -3,31 +3,50 @@
33
[![Latest Version](https://img.shields.io/github/release/omaralalwi/php-builders.svg?style=flat-square)](https://github.com/omaralalwi/php-builders/releases)
44
[![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)
55

6-
**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.
6+
**PHP Builders** is a lightweight PHP library designed to simplify the implementation of the Builder design pattern in PHP applications.
7+
8+
---
79

810
## Table of Contents
911

1012
- [Installation](#installation)
1113
- [Usage](#usage)
12-
- [Creating a Builder Class](#creating-a-builder-class)
13-
- [Using the Builder](#using-the-builder)
14+
- [By Extending `Fluentbuilder` in Builder Class](#by-extending-fluentbuilder-in-builder-class)
15+
- [By Include Traits in Builder Class](#by-include-traits)
16+
- [Cast Builder Class](#cast-builder-class)
17+
- [Return as Array](#return-as-array)
18+
- [Return as Object](#return-as-object)
19+
- [Return as JSON](#return-as-json)
20+
- [Custom Execution Logic](#custom-execution-logic)
1421
- [Contributing](#contributing)
1522
- [Security](#security)
1623
- [License](#license)
1724

25+
---
26+
1827
## Installation
1928

20-
You can install the package via Composer. Run the following command in your terminal:
29+
Install the package via Composer using the following command:
2130

2231
```bash
2332
composer require omaralalwi/php-builders
2433
```
2534

35+
---
36+
2637
## Usage
2738

28-
### Creating a Builder Class
39+
**Note**: if you not use any PHP frameworks like (symfony,laravel,codeigniter,Yii,cakePHP..etc), you should add this line:
40+
41+
```php
42+
require_once __DIR__ . '/vendor/autoload.php';
43+
```
44+
45+
**First Way**
46+
47+
### By Extending FluentBuilder in Builder Class
2948

30-
To create a builder class, extend the `FluentBuilder` class and define your properties and methods.
49+
The `FluentBuilder` class integrates all available traits, enabling you to utilize all package features by simply extending this class.
3150

3251
```php
3352
namespace App\Builders;
@@ -38,7 +57,7 @@ class UserBuilder extends FluentBuilder
3857
{
3958
protected string $name;
4059
protected string $email;
41-
60+
4261
public function setName(string $name): self
4362
{
4463
$this->name = $name;
@@ -50,58 +69,154 @@ class UserBuilder extends FluentBuilder
5069
$this->email = $email;
5170
return $this;
5271
}
53-
72+
5473
public function sendEmail(): self
5574
{
56-
// handle send email to user or make any action
57-
// then return instance of self
58-
return $this;
75+
// Logic for sending an email
76+
return $this;
5977
}
60-
61-
// add any another functions then call them as you need
6278
}
6379
```
6480

65-
### Using the Builder
81+
**second Way**
6682

67-
You can convert the built instance to an array or an object using the `toArray()` and `toObject()` methods.
83+
### By Include Traits
6884

69-
#### Return Array
85+
simplify you can achieve same result by include `Buildable`, `Arrayable`, `Objectable`, `Jsonable` traits directly in builder class, without extending the `FluentBuilder` class.
7086

7187
```php
72-
$userArray = UserBuilder::build()
73-
->setName('PHP Builders')
74-
->setEmail('[email protected]')
75-
->sendEmail()
76-
->toArray();
88+
namespace App\Builders;
89+
90+
use Omaralalwi\PhpBuilders\Traits\{Buildable, Arrayable, Objectable, Jsonable};
91+
use App\Models\User;
7792

78-
getType($userArray) // Array
79-
$userArray['name'] // PHP Builders
80-
$userArray['email'] // [email protected]
93+
class UserBuilder
94+
{
95+
use Buildable,
96+
Arrayable,
97+
Objectable,
98+
Jsonable;
99+
100+
// same code in first way example
101+
}
81102
```
82103

83-
#### Return Object
104+
### cast Builder Class
105+
106+
use `UserBuilder` as following:
84107

85108
```php
86-
$userObject = UserBuilder::build()
109+
$user = UserBuilder::build()
87110
->setName('PHP Builders')
88-
->setEmail('[email protected]')
89-
->sendEmail()
90-
->toObject();
111+
->setEmail('[email protected]')
112+
->sendEmail();
113+
```
114+
then cast it to needed type as following:
115+
116+
**Return as Array**
117+
118+
Convert the built instance to an array using the `toArray()` method:
119+
120+
```php
121+
$userAsArray = $user->toArray();
122+
print_r($userAsArray);
123+
/*
124+
Output:
125+
Array
126+
(
127+
[name] => PHP Builders
128+
[email] => [email protected]
129+
)
130+
*/
131+
```
132+
133+
**Return as Object**
91134

92-
getType($userArray) // object
93-
$userArray->name // PHP Builders
94-
$userArray->email // [email protected]
135+
Convert the built instance to an object using the `toObject()` method:
136+
137+
```php
138+
$userAsObject = $user->toObject();
139+
print_r($userAsObject);
140+
/*
141+
Output:
142+
stdClass Object
143+
(
144+
[name] => PHP Builders
145+
[email] => [email protected]
146+
)
147+
*/
95148
```
96149

150+
**Return as JSON**
151+
152+
Convert the built instance to JSON using the `toJson()` method:
153+
154+
```php
155+
$userAsJson = $user->toJson();
156+
echo $userAsJson;
157+
/*
158+
Output:
159+
{"name":"PHP Builders","email":"[email protected]"}
160+
*/
161+
```
162+
163+
---
164+
165+
#### Custom Execution Logic
166+
167+
```php
168+
namespace App\Builders;
169+
170+
use Omaralalwi\PhpBuilders\FluentBuilder;
171+
use App\Models\User;
172+
173+
class UserBuilder extends FluentBuilder
174+
{
175+
// same code in previous example, just we added execute method .
176+
177+
public function execute(): User
178+
{
179+
// Pre-store logic (e.g., validation, preprocessing)
180+
return $this->store();
181+
}
182+
183+
protected function store(): User
184+
{
185+
return User::create([
186+
'name' => $this->name,
187+
'email' => $this->email,
188+
]);
189+
}
190+
}
191+
```
192+
193+
```php
194+
$createdUser = UserBuilder::build()
195+
->setName('PHP Builders')
196+
->setEmail('[email protected]')
197+
->execute();
198+
/*
199+
$createdUser is an instance of the User model.
200+
*/
201+
```
202+
203+
> **Note:** Traits like `Arrayable`, `Objectable`, and `Jsonable` can also be included in your builder class as needed if you choose not to extend `FluentBuilder`.
204+
205+
---
206+
97207
## Contributing
98208

99-
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](https://github.com/omaralalwi/php-builders).
209+
Contributions are welcome! To propose improvements or report issues, please open an issue or submit a pull request on the [GitHub repository](https://github.com/omaralalwi/php-builders).
210+
211+
---
100212

101213
## Security
102214

103-
If you discover any security-related issues, please email creator : `[email protected]`.
215+
If you discover any security-related issues, please email the author at: `[email protected]`.
216+
217+
---
104218

105219
## License
106220

107-
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
221+
This project is open-source and licensed under the [MIT License](LICENSE).
222+

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
"homepage": "https://github.com/omaralalwi/php-builders",
1919
"license": "MIT",
2020
"type": "library",
21-
"version": "1.0.0",
21+
"version": "1.0.1",
2222
"authors": [
2323
{
2424
"name": "omar alalwi",

src/FluentBuilder.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
namespace Omaralalwi\PhpBuilders;
44

5-
use Omaralalwi\PhpBuilders\Traits\{Buildable, Arrayable, Objectable};
5+
use Omaralalwi\PhpBuilders\Traits\{Buildable, Arrayable, Objectable, Jsonable};
66

77
class FluentBuilder
88
{
9-
use Buildable, Arrayable, Objectable;
9+
use Buildable,
10+
Arrayable,
11+
Objectable,
12+
Jsonable;
1013
}

src/Traits/Jsonable.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Omaralalwi\PhpBuilders\Traits;
4+
5+
trait Jsonable
6+
{
7+
public function toJson(): string
8+
{
9+
$properties = [];
10+
$reflection = new \ReflectionClass($this);
11+
foreach ($reflection->getProperties() as $property) {
12+
$property->setAccessible(true);
13+
$properties[$property->getName()] = $property->getValue($this);
14+
}
15+
return json_encode($properties);
16+
}
17+
}

0 commit comments

Comments
 (0)