ifcanduela / container
简单的键/值容器
1.0.1
2022-02-09 09:34 UTC
Requires
- php: ^7.4|^8.0
Requires (Dev)
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.10
This package is auto-updated.
Last update: 2024-09-09 15:09:00 UTC
README
非常简单的键/值容器,灵感来自Pimple。
安装
使用 Composer
composer require ifcanduela/container
用法
创建一个 ifcanduela\container\Container
实例开始。传递关联数组中的值是可选的,可以使用 merge()
方法稍后完成。
$container = new ifcanduela\container\Container([ "alpha" => "a", "beta" => "b", ]); $container->merge([ "gamma" => "g", "delta" => "d", ]);
简单值
使用 set()
注册值,使用 get()
获取值。
$container->set("db_username", "root@localhost"); echo $container->get("db_username");
Container 类实现了 ArrayAccess
,因此可以使用索引符号设置和获取值。
$container["db_username"] = "root@localhost"; echo $container["db_username"];
闭包
可以通过两种方式添加闭包:如果您的意图是访问闭包本身,请使用 raw()
方法,或者将其包装在 raw()
函数的调用中。
use function ifcanduela\container\raw; $container->raw("rand", function (int $max) { return random_int(0, $max); }); // using the helper $container->set("rand", raw(function (...) {...})); // using array index notation $container["rand"] = raw(function (...) {...}); $rand = $container->get("rand"); echo $rand(100);
如果您想使用闭包来构建值,只需使用 set()
。这些闭包仅在调用 get()
时运行,将接收容器本身,并且只执行一次(每次调用 get()
都返回相同的结果)。
$container->set("logger", function (Container $c) { return new Logger($c->get("log_path")); }); // using array index notation $container["logger"] = function (...) {...}; $logger = $container->get("logger"); $logger->log(Logger::INFO, "I'm the logger");
工厂
如果闭包必须在每次读取值时调用,例如构建对象的多个实例,请使用 factory()
或使用 factory()
函数包装它来定义。
use function ifcanduela\container\factory; $container->factory("rand", function (Container $c) { return random_int(0, $c->get("max_random_number")); }); // using the helper $container->set("rand", factory(function (...) {...})); // using array index notation $container["rand"] = factory(function (...) {...}); echo $container->get("rand"); // => 24 echo $container->get("rand"); // => 71 echo $container->get("rand"); // => 13
检查值是否已定义
使用 has()
方法,或在使用数组索引符号时使用 isset()
。
$container = new \ifcanduela\container\Container([ "a" => 1, "b" => 2, "c" => 3, "e" => 5, ]); var_dump($container->has("a")); // => true var_dump($container->has("d")); // => false var_dump(isset($container["d"])); // => false
许可
MIT.