Skip to content

API Reference

Azizul Hakim edited this page Jun 12, 2025 · 2 revisions

Complete reference for all Laravel Setanjo methods and classes.

Facade Methods

Settings Facade

use Ahs12\Setanjo\Facades\Settings;

Global Settings Methods

set(string $key, mixed $value): SetanjoManager

Set a global setting value.

Settings::set('app_name', 'My Application');
Settings::set('maintenance_mode', false);
Settings::set('max_users', 100);
Settings::set('features', ['api', 'webhooks']);

Parameters:

  • $key (string): Setting key name
  • $value (mixed): Value to store (auto-typed)

Returns: SetanjoManager instance for method chaining


get(string $key, mixed $default = null): mixed

Get a global setting value.

$appName = Settings::get('app_name');
$maxUsers = Settings::get('max_users', 50); // With default
$nonExistent = Settings::get('missing_key', 'fallback');

Parameters:

  • $key (string): Setting key name
  • $default (mixed): Default value if key doesn't exist

Returns: Setting value or default


has(string $key): bool

Check if a global setting exists.

if (Settings::has('app_name')) {
    echo 'App name is configured';
}

Parameters:

  • $key (string): Setting key name

Returns: true if setting exists, false otherwise


forget(string $key): SetanjoManager

Remove a global setting.

Settings::forget('old_setting');

Parameters:

  • $key (string): Setting key name

Returns: SetanjoManager instance


all(): Collection

Get all global settings.

$allSettings = Settings::all();
foreach ($allSettings as $setting) {
    echo "{$setting->key}: {$setting->value}";
}

Returns: Laravel Collection of Setting models


flush(): SetanjoManager

Remove all global settings.

Settings::flush(); // Removes all global settings

Returns: SetanjoManager instance


Tenant-Specific Methods

for(Model $tenant): SetanjoManager

Set the tenant context for subsequent operations.

$user = User::find(1);
$company = Company::find(1);

Settings::for($user)->set('theme', 'dark');
Settings::for($company)->set('plan', 'premium');

Parameters:

  • $tenant (Model): Eloquent model instance

Returns: New SetanjoManager instance scoped to tenant


forTenantId(int $tenantId, ?string $modelClass = null): SetanjoManager

Set tenant context by ID and model class.

// Strict mode (model class inferred)
Settings::forTenantId(1)->set('theme', 'dark');

// Polymorphic mode (model class required)
Settings::forTenantId(1, User::class)->set('theme', 'dark');
Settings::forTenantId(5, Company::class)->set('plan', 'enterprise');

Parameters:

  • $tenantId (int): Tenant model ID
  • $modelClass (string|null): Model class name (required in polymorphic mode)

Returns: New SetanjoManager instance scoped to tenant

Throws: InvalidTenantException if tenant not found


SetanjoManager Class

Method Chaining

All setter methods return SetanjoManager instances, enabling method chaining:

Settings::for($user)
    ->set('theme', 'dark')
    ->set('language', 'en')
    ->set('notifications', true);

// Or with global settings
Settings::set('app_name', 'My App')
    ->set('maintenance_mode', false)
    ->set('registration_enabled', true);

Tenant Context

Once you call for() or forTenantId(), all subsequent operations on that instance are scoped to that tenant:

$userSettings = Settings::for($user);

$userSettings->set('theme', 'dark');
$userSettings->set('language', 'en');
$theme = $userSettings->get('theme'); // 'dark'

// Global settings remain unaffected
$globalTheme = Settings::get('theme'); // null or global value

Type Casting

Setanjo automatically detects and converts data types:

Supported Types

// String (default)
Settings::set('name', 'John Doe');
$name = Settings::get('name'); // string

// Boolean
Settings::set('enabled', true);
$enabled = Settings::get('enabled'); // boolean true

// Integer
Settings::set('count', 42);
$count = Settings::get('count'); // int 42

// Float
Settings::set('price', 19.99);
$price = Settings::get('price'); // float 19.99

// Array
Settings::set('tags', ['php', 'laravel']);
$tags = Settings::get('tags'); // array ['php', 'laravel']

// JSON String (detected automatically)
Settings::set('config', '{"theme": "dark", "lang": "en"}');
$config = Settings::get('config'); // array ['theme' => 'dark', 'lang' => 'en']

// Object
Settings::set('metadata', (object)['version' => '1.0']);
$metadata = Settings::get('metadata'); // stdClass object

Type Detection Rules

  1. Boolean: true/false values
  2. Integer: Whole numbers
  3. Float: Decimal numbers
  4. Array: PHP arrays
  5. Object: PHP objects
  6. JSON: Valid JSON strings (auto-parsed to arrays)
  7. String: Everything else (default)

Repository Interface

SettingsRepositoryInterface

Implement this interface to create custom repositories:

interface SettingsRepositoryInterface
{
    public function get(string $key, $default = null, $tenant = null);
    public function set(string $key, $value, $tenant = null): void;
    public function has(string $key, $tenant = null): bool;
    public function forget(string $key, $tenant = null): void;
    public function all($tenant = null);
    public function flush($tenant = null): void;
}

Custom Repository Example

class RedisSettingsRepository implements SettingsRepositoryInterface
{
    public function get(string $key, $default = null, $tenant = null)
    {
        $cacheKey = $this->buildCacheKey($key, $tenant);
        return Redis::get($cacheKey) ?? $default;
    }
    
    public function set(string $key, $value, $tenant = null): void
    {
        $cacheKey = $this->buildCacheKey($key, $tenant);
        Redis::set($cacheKey, serialize($value));
    }
    
    // ... implement other methods
}

Exception Handling

InvalidTenantException

Thrown when tenant validation fails:

use Ahs12\Setanjo\Exceptions\InvalidTenantException;

try {
    // In strict mode with User model configured
    $company = new Company();
    Settings::for($company)->set('theme', 'dark');
} catch (InvalidTenantException $e) {
    echo $e->getMessage(); // "Invalid tenant type. Expected instance of [App\Models\User], got [App\Models\Company]."
    
    $tenant = $e->getTenant(); // The invalid tenant object
    $allowedTypes = $e->getAllowedTypes(); // Array of allowed classes
}

Exception Methods

// Static factory methods
InvalidTenantException::forStrictMode($tenant, $expectedClass);
InvalidTenantException::forPolymorphicMode($tenant, $allowedClasses);
InvalidTenantException::notFound($modelClass, $tenantId);
InvalidTenantException::missingConfiguration($configKey);

// Instance methods
$exception->getTenant(); // Get the invalid tenant
$exception->getAllowedTypes(); // Get allowed tenant types
$exception->getTenantClass(); // Get tenant class name

Setting Model

Eloquent Model

The Setting model represents stored settings:

use Ahs12\Setanjo\Models\Setting;

$setting = Setting::where('key', 'app_name')->first();
echo $setting->key;         // 'app_name'
echo $setting->value;       // 'My Application' (properly typed)
echo $setting->type;        // SettingType::STRING
echo $setting->description; // Optional description

Model Properties

class Setting extends Model
{
    protected $fillable = [
        'key',
        'value', 
        'description',
        'type',
    ];
    
    protected $casts = [
        'type' => SettingType::class,
    ];
}

Relationships

// Get tenant (polymorphic relationship)
$tenant = $setting->tenantable; // User, Company, etc.

// Query scopes
Setting::global()->get(); // Global settings only
Setting::forTenant($user)->get(); // Tenant-specific settings

Enums

SettingType Enum

use Ahs12\Setanjo\Enums\SettingType;

enum SettingType: string
{
    case STRING = 'string';
    case BOOLEAN = 'boolean';
    case INTEGER = 'integer';
    case FLOAT = 'float';
    case ARRAY = 'array';
    case JSON = 'json';
    case OBJECT = 'object';
}

// Static method for type detection
$type = SettingType::fromValue($someValue);

Advanced Usage Examples

Batch Operations

// Set multiple settings for a tenant
$user = User::find(1);
$userSettings = Settings::for($user);

$userSettings
    ->set('theme', 'dark')
    ->set('language', 'en')
    ->set('timezone', 'America/New_York')
    ->set('notifications', [
        'email' => true,
        'push' => false,
        'sms' => true
    ]);

Conditional Settings

// Set setting only if it doesn't exist
if (!Settings::has('api_key')) {
    Settings::set('api_key', Str::random(32));
}

// Get with dynamic default
$maxUsers = Settings::get('max_users', config('app.default_max_users'));

Complex Data Types

// Store complex configuration
Settings::set('email_config', [
    'driver' => 'smtp',
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'encryption' => 'tls',
    'credentials' => [
        'username' => '[email protected]',
        'password' => 'secret'
    ]
]);

$emailConfig = Settings::get('email_config');
// Returns properly typed array with nested structure

Per-Tenant Feature Flags

// Enable features per tenant
$company = Company::find(1);
Settings::for($company)->set('features', [
    'api_access' => true,
    'advanced_reporting' => false,
    'custom_branding' => true
]);

// Check feature availability
$features = Settings::for($company)->get('features', []);
if ($features['api_access'] ?? false) {
    // Grant API access
}

📚 Documentation Structure

Home

  • Home - Homepage of the wiki

Getting Started

Core Concepts

API Reference

Advanced Usage

  • Commands - Artisan commands for management

Tips

🤝 Community

Clone this wiki locally