1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Ui;
6:
7: use Atk4\Core\TraitUtil;
8:
9: trait SessionTrait
10: {
11: private function getSessionManager(): App\SessionManager
12: {
13: // all methods use this method, so we better check NameTrait existence here in one place
14: if (!TraitUtil::hasNameTrait($this)) {
15: throw new Exception('Object must have NameTrait applied to use session');
16: }
17:
18: return $this->getApp()->session;
19: }
20:
21: /**
22: * @template T
23: *
24: * @param \Closure(): T $fx
25: *
26: * @return T
27: */
28: public function atomicSession(\Closure $fx, bool $readAndCloseImmediately = false)
29: {
30: return $this->getSessionManager()->atomicSession($fx, $readAndCloseImmediately);
31: }
32:
33: /**
34: * Remember data in object-relevant session data.
35: *
36: * @param mixed $value
37: *
38: * @return mixed $value
39: */
40: public function memorize(string $key, $value)
41: {
42: return $this->getSessionManager()->memorize($this->name, $key, $value);
43: }
44:
45: /**
46: * Similar to memorize, but if value for key exist, will return it.
47: *
48: * @param mixed $defaultValue
49: *
50: * @return mixed Previously memorized data or $defaultValue
51: */
52: public function learn(string $key, $defaultValue = null)
53: {
54: return $this->getSessionManager()->learn($this->name, $key, $defaultValue);
55: }
56:
57: /**
58: * Returns session data for this object. If not previously set, then
59: * $defaultValue is returned.
60: *
61: * @param mixed $defaultValue
62: *
63: * @return mixed Previously memorized data or $defaultValue
64: */
65: public function recall(string $key, $defaultValue = null)
66: {
67: return $this->getSessionManager()->recall($this->name, $key, $defaultValue);
68: }
69:
70: /**
71: * Forget session data for $key. If $key is omitted will forget all
72: * associated session data.
73: *
74: * @return $this
75: */
76: public function forget(string $key = null)
77: {
78: $this->getSessionManager()->forget($this->name, $key);
79:
80: return $this;
81: }
82: }
83: