-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcounter.php
More file actions
50 lines (36 loc) 路 1.44 KB
/
Copy pathcounter.php
File metadata and controls
50 lines (36 loc) 路 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
// this is the default namespace; can be specified in build()
namespace App;
require_once dirname(__DIR__) . '/vendor/autoload.php';
use Elephox\Miniphox\Miniphox;
use Elephox\Web\Routing\Attribute\Http\Get;
use stdClass;
// suppose we have these services:
class TransientCounter {
public int $value = 0;
}
class SingletonCounter {
public int $value = 0;
}
// and this endpoint:
#[Get('/count')]
function count(TransientCounter $transientCounter, SingletonCounter $singletonCounter): array
{
// The counters will get injected from the services specified below.
// Value will only increase above 1 on the singleton since the transient counter is re-created every time it is
// requested.
$transientCounter->value++;
$singletonCounter->value++;
return [
'transient' => $transientCounter->value,
'singleton' => $singletonCounter->value,
];
}
// build the app and register our services
$app = Miniphox::build()->mount('/api', count(...));
// transient services get created every time they are requested (unlike singletons)
$app->getServices()->addTransient(TransientCounter::class, TransientCounter::class, fn() => new TransientCounter());
// singleton services are only created once and are then kept in memory for repeated use of the same instance
$app->getServices()->addSingleton(SingletonCounter::class, SingletonCounter::class, fn() => new SingletonCounter());
$app->run();