Skip to content

Commit 5b0ec64

Browse files
author
nix
committed
added With class; added branch-alias to composer.json
1 parent 06846fb commit 5b0ec64

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,32 @@ echo (new Pipe('NOW')) // wrap initial value
187187
// prints: 2026
188188
```
189189

190+
### With
191+
192+
A `With` object wraps an object and can be used to call any method on it with chaining support (handled by the wrapper).
193+
Note that any value returned by the method calls is discarded!
194+
195+
```php
196+
With::new(mysqli::class, 'localhost', 'db_user', 'db_password')
197+
->set_charset('utf8mb4')
198+
->select_db('log')
199+
->autocommit(false)
200+
->begin_transaction()
201+
->execute_query('INSERT INTO ping')
202+
->execute_query('INSERT INTO pong')
203+
->commit()
204+
->close();
205+
```
206+
207+
Or just use it for initialization calls and unwrap it then:
208+
```php
209+
$mysql = With::new(mysqli::class, 'localhost', 'db_user', 'db_password')
210+
->set_charset('utf8mb4')
211+
->select_db('log')
212+
->autocommit(false)
213+
->object; // unwrap
214+
```
215+
190216
## License
191217
Copyright © 2025 nix <https://keybase.io/nixn>
192218

composer.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,10 @@
1515
"psr-4": {
1616
"nixn\\php\\": "src/"
1717
}
18+
},
19+
"extra": {
20+
"branch-alias": {
21+
"dev-main": "1.1.x-dev"
22+
}
1823
}
1924
}

src/With.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
namespace nixn\php;
3+
4+
/** @since 1.1 */
5+
final class With
6+
{
7+
/**
8+
* @template T
9+
* @param class-string<T> $class
10+
* @param mixed ...$args
11+
* @return T
12+
* @since 1.1
13+
*/
14+
public static function new(string $class, mixed ...$args): object
15+
{
16+
return new $class(...$args);
17+
}
18+
19+
public function __construct(
20+
public object $object,
21+
)
22+
{}
23+
24+
public function __call(string $method, array $args)
25+
{
26+
$this->object->{$method}(...$args);
27+
return $this;
28+
}
29+
30+
public function __toString(): string
31+
{
32+
return "$this->object";
33+
}
34+
}

0 commit comments

Comments
 (0)