azjezz / typed
PHP 7.4+ 的类型变量
0.0.2
2019-01-14 21:25 UTC
Requires
- php: ^7.4.0
This package is auto-updated.
Last update: 2024-09-19 08:52:09 UTC
README
此库允许您在 PHP 7.4+ 中创建类型变量
Composer 安装
$ composer require azjezz/typed
使用示例
<?php declare(strict_types=1); use Typed as t; $name = &t\string('saif'); $age = &t\int(19); try { $name = 'azjezz'; // works $name = 15; // fails $age = null; // fails } catch(TypeError $error) { } finally { t\clean(); }
callable => func
, array => { arr
, keyset
, vector
, set
}
由于 callable
和 array
不能用作函数名,因此我使用了 func
来表示可调用对象,arr
来表示数组。《keyset》、《vector》和《set》只是辅助函数,帮助您创建键数组(keyset = arr(array_keys($value))
)、值数组(vector = arr(array_values($value))
)和唯一值数组(set = arr(array_unique($value))
)。
typed
typed()
是一个函数,帮助您根据传入变量的类型创建类型变量,目前它支持 string
、int
、float
、bool
、object
和 iterable
。它是由 @mikesherov 在 twitter 上提出的。
purge
、clean
、delete
和 c
如 此处 和 此处 所述,内存泄漏是一个大问题,如果某个特定函数创建了一个类型变量,则变量即使在执行后仍然存在于存储库中,因此我创建了一些辅助函数,允许您从存储库中删除变量。
Typed\purge()
将删除存储库中注册的所有引用,例如,您可以在 Web 应用程序中在每个请求/响应周期结束时调用此函数。Typed\clean(string $namespace = 'default')
此函数将删除特定命名空间中所有类型变量的引用,如图例所示,每次使用类型变量时都建议使用唯一的命名空间,并调用clean()
以确保没有内存泄漏。Typed\filter(mixed $value, string $namespace = 'default')
此函数将删除特定命名空间中具有给定值的每个已创建类型变量的引用。Typed\delete(mixed $value, string $namespace = 'default')
与Typed\filter
类似,此函数允许您删除特定命名空间中具有给定值的最后一个创建的类型变量的引用。例如
<?php declare(strict_types=1); use Typed as t; $name = &t\string('azjezz', 'data'); $age = &t\int(19, 'data'); t\delete($name, 'data'); /** * the reference to the `$name` variable has been deleted. * therefor we can assign any type to the variable `$name` now. */ $name = []; // works
Typed\c
此函数接受一个不带参数的可调用对象,该可调用对象将在c
(容器)内调用,并在调用时删除所有分配的类型变量,这使得确保函数调用不会引起任何内存泄漏变得更容易。例如
<?php declare(strict_types=1); use Typed as t; use function Typed\c; /** * all assigned variables inside the callable will be destroyed after execution. */ c(function(): void { $name = &t\string('saif eddin'); $age = &t\int(5); $arr = &t\arr([ 'age' => $age, 'name' => $name ]); });
更多
一个酷的 PSR-15 中间件,用于删除下一个中间件/处理程序中创建的所有类型变量
<?php declare(strict_types=1); use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use function Typed\c; class TypedMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = null; c(function() use($request, &$response, $handler) { /** * if any typed variable is created in the handler, it would be deleted after execution. */ $response = $handler->handle($request); }); return $response; } }
待办事项
- 添加
nullable*
函数。