vildanhakanaj/php-options

简单地在网站上与选项数组交互的方法

v0.2.0 2024-04-28 03:09 UTC

This package is auto-updated.

Last update: 2024-09-28 04:01:57 UTC


README

为网站、文章、页面等管理选项数组的一个简单方法。

要求

  • php 7.4 及以上

安装

使用 composer

composer require vildanhakanaj/php-options 

用法

实例化

use VildanHakanaj\Options;

$options = new Options([
    "key1" => "value1",
    "key2" => "value2"
]);
// or
$options = Options::fromArray([
    "key1" => "value1",
    "key2" => "value2"
]);

设置选项

// Set options
// Use magic setters
$options->key = "value";
// Merge with key value
$options->mergeKey("key", "value");
// Merge an array with key values
$options->merge(["key" => "value", "key1" => "value1"]);
// override options with the given array 
$options->override(["newKey" => "newValue"]);
// Only add if its not already in the options
$options->addIfUnique("key", "value");

访问选项

// Any of the merge operations will override if any of the keys already exists in the options array.
// get value out of options
//Will return null if the key is not found
$value = $options->get("key");
$value = $options->key;
$value = $options["key"];
//Get all values
$values = $options->values();
//Get all keys
$keys = $options->keys();
//Get all options
$array = $options->all();
//Check if the key is in options array
$boolean = $options->has("key");

过滤选项

//Filter by value
$filteredOptions = $options->filter(function($option){
    return true; /*logic for filtering*/
});
// Remove the falsy values
$onlyTruthyValues = $options->filter();
//Filter by key
$filteredOptions = $options->filterByKey(function($option){
    return true; /*logic for filtering*/
});

可迭代

foreach(Option::fromArray(["key" => "value"]) as $optionKey => $optionValue){
    // $optionKey = "key";
    // $optionValue = "value";
}