Settings Usage - 10quality/wpmvc-addon-administrator GitHub Wiki

The model can be used as a regular Option Model. Although, if correctly configured, it will include additional features.

Instance

Every settings model can be loaded and accessed by calling to its static instance, see an example:

use [Namespace]\Models\Settings;

$settings = Settings::instance();

Or:

$settings = [Namespace]\Models\Settings::instance();

Get a field value

To get the value of a saved field, simply use the field ID as a settings property.

For example, if the model has defined the following field ID (api_key):

// Namespace and use statement...
class Settings extends Model
{
    // Class properties...
    protected function init()
    {
        // Other properties...
        $this->tabs = [
            'tab_id' => [
                'fields' => [
                    'api_key' => [
                        'title' => __( 'API Key', 'my-domain' ),
                    ],
                ],
            ],
        ];
    }
}

The value can be retrieved as property, like this:

use [Namespace]\Models\Settings;
$api_key = Settings::instance()->api_key;

Or:

$api_key = [Namespace]\Models\Settings::instance()->api_key;

Aliases

The model can still use aliases on top of the settings fields, for example:

// Namespace and use statement...
class Settings extends Model
{
    /**
     * Aliases.
     * Mapped against custom fields functions.
     * @var array
     */
    protected $aliases = [
        'property_not_in_settings' => 'field_not_in_settings',
        'is_api_key_valid' => 'func_get_is_api_key_valid',
    ];
    // Class properties...
    protected function init()
    {
        // Other properties...
    }
    protected function get_is_api_key_valid()
    {
        return $this->api_key && strlen( $this->api_key ) > 10;
    }
}

Which can also be accessed with the instance:

use [Namespace]\Models\Settings;
$settings= Settings::instance();

if ( $settings->is_api_key_valid ) {
    echo $settings->api_key;
}

Save model

The settings model can be saved outside of the auto-generated settings pages using the method save(), use this with discretion as this option will not apply sanitization nor validation on the data.

use [Namespace]\Models\Settings;

$settings= Settings::instance();

$settings->api_key = 'New_Api_key';
$settings->save();