PHP code example of typisttech / wp-option-store

1. Go to this page and download the library: Download typisttech/wp-option-store library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

typisttech / wp-option-store example snippets


use TypistTech\WPOptionStore\Factory;

// By default, the `Factory` adds 2 strategies (order matters):
//  1. ConstantStrategy
//  2. DatabaseStrategy
$filteredOptionStore = Factory::build();

// To get an option from strategies:
//  1. Read `MY_OPTION` constant
//  2. If (1) is not `null`, jump to (6)
//  3. Read from `get_option('my_option')`, the normal WordPress Options API
//  4. If (3) is not `null`, jump to (6)
//  5. We have tried all strategies, pass `null` to (6)
//  6. Pass whatever we have read (could be null) through `apply_filters('my_option', $whateverWeHaveRead);`
$filteredOptionStore->get('my_option');

// To get an option and perform type cast.
$filteredOptionStore->getBoolean('my_boolean_option');
$filteredOptionStore->getInt('my_integer_option');
$filteredOptionStore->getString('my_string_option');
$filteredOptionStore->getArray('my_array_option');

define('MY_OPTION', 'abc123');

$strategy = new ConstantStrategy();

$value1 = $strategy->get('my_option');
// $value1 === 'abc123';

$value2 = $strategy->get('my_non_exist_option');
// $value2 === null;

update_option('my_option', 'abc123');

$strategy = new DatabaseStrategy();

$value1 = $strategy->get('my_option');
// $value1 === 'abc123';

$value2 = $strategy->get('my_non_exist_option');
// $value2 === null;

$databaseStrategy = new DatabaseStrategy();
$constantStrategy = new ConstantStrategy();
$optionStore = new OptionStore($constantStrategy, $databaseStrategy);

// It returns the first non-null value from strategies.
define('MY_OPTION', 'abc');
update_option('my_option', 'xyz');

$value1 = $optionStore->get('my_option');
// $value1 === 'abc';

// It returns `null` when option not found.
$value2 = $optionStore->get('my_non_exist_option');
// $value2 === null;

$optionStore->getBoolean('my_boolean_option');
$optionStore->getInt('my_integer_option');
$optionStore->getString('my_string_option');
$optionStore->getArray('my_array_option');

// It returns the first non-null value from strategies,
// and applies filters.
define('MY_OPTION', 'abc');
update_option('my_option', 'xyz');

add_filter('my_option', function($value) {
    return 'filtered ' . $value;
});

$value = $filteredOptionStore->get('my_option');
// $value === 'filtered abc';

$filteredOptionStore = Factory::build();

// Order matters!
$optionStore = new FilteredOptionStore(
    new MyStrategy1(),
    new MyStrategy2(),
    new MyStrategy3(),
);