Milk Admin

Get Class

The Get Class is a facade class to facilitate access and management of core system functionalities such as database connections, email sending, module and module loading, and theme page and module management.

Below is a quick summary of the available methods, followed by detailed sections.

Method Summary

Method Parameters Return Description
db() - MySql|SQLite|ArrayDb|null Returns the primary database connection (singleton).
db2() - MySql|SQLite|ArrayDb|null Returns the secondary database connection (singleton).
dbConnection(string $name) connection name MySql|SQLite|ArrayDb Returns a named database connection.
arrayDb() - ArrayDb Returns the in-memory ArrayDB adapter (singleton).
schema($table, $db = null) table, db SchemaMysql|SchemaSqlite Returns a schema helper for a table.
mail() - Mail Returns the configured mailer instance.
loadModules() - void Loads modules and theme plugins.
themePlugin(string $module, array $variables = []) module, variables string Loads a theme plugin and returns its output.
dirPath(string $file) absolute path string Resolves a safe file path inside project roots.
uriPath(string $file) file path string Builds the public URI for a file.
tempDir() - string Returns the temp directory path.
dateTimeZone() - DateTime Returns a DateTime in the configured timezone.
formatDate($date, string $format = 'date', bool $timezone = false) date, format, timezone string Formats dates with locale-aware patterns.
userTimezone() - string Returns the current user timezone.
setUserTimezone(?string $timezone) timezone void Overrides timezone for the current request.
userLocale() - string Returns the current user locale.
setUserLocale(?string $locale) locale void Overrides locale for the current request.
bind($service, $implementation, bool $singleton = false, array $arguments = []) service, implementation, singleton, args void Registers a service in the container.
make($name, array $arguments = []) name, args mixed Creates a service from the container.
has($name) name bool Checks if a service is registered.
clientIp(bool $trust_proxy_headers = false) trust proxy string Returns the client IP address.
closeConnections() - void Closes db/db2 connections and resets the singletons.

Database Management

db()

Creates or returns an instance of the primary system database connection. Implements the singleton pattern and supports both MySQL and SQLite. The database type is determined by the 'db_type' configuration.

// Get database connection and run a query
$db = Get::db();
$results = $db->query("SELECT * FROM users WHERE active = 1");

db2()

Creates or returns an instance of the secondary database connection. The system can use two databases: one for configuration and one for data. This method handles the connection to the secondary database (for data).

// Get secondary database connection
$db2 = Get::db2();
$results = $db2->query("SELECT * FROM data_table WHERE status = 'active'");

dbConnection(string $name)

Returns a named database connection from the configuration or runtime additions. Useful when you define more than two connections.

// Get a custom connection
$analytics = Get::dbConnection('analytics');

arrayDb()

Returns the ArrayDB adapter (in-memory database) as a singleton. It is initialized with an ArrayEngine and can be populated via addTable() or connect().

// In-memory database
$arrayDb = Get::arrayDb();
$arrayDb->addTable('users', [
    ['id' => 1, 'name' => 'Mario'],
    ['id' => 2, 'name' => 'Laura'],
], 'id');

schema($table, $db = null)

Returns a schema instance for the specified table. Supports both MySQL and SQLite and uses the appropriate class based on the configured database type.

$schema = Get::schema('users');
// Or with specific database
$schema = Get::schema('users', Get::db2());

closeConnections()

Closes the primary and secondary connections and resets their singletons. This is useful in long-running scripts or CLI tasks.

Get::closeConnections();

Email Management

mail()

Creates or returns an instance of the Mail class for sending emails. Implements the singleton pattern and automatically configures itself with SMTP settings from the configuration file.

// Send an email
Get::mail()
    ->to('recipient@example.com')
    ->from('sender@example.com')
    ->subject('Hello')
    ->message('This is a test email')
    ->send();

Module and Theme Management

loadModules()

Loads all module modules and theme functions. This method initializes all module modules and theme functions required for the application to work properly.

Get::loadModules();

themePlugin($module, $variables)

Loads the requested theme plugin passing the necessary variables. Returns the content of the loaded module.

$content = Get::themePlugin('sidebar', ['active' => 'home']);

Path and URI Management

dirPath($file)

Returns the secure path of a file. Protects against path traversal attacks by ensuring paths remain within the site directory. Also checks for customization files with the same name in the milkadmin_local directory.

$file = Get::dirPath(THEME_DIR.'/template_parts/sidebar.php');

uriPath($file)

Returns the URI path for resources like JS or CSS files. Handles theme milkadmin_local and proper URL formatting.

<img src="<?php echo Get::uriPath($path); ?>" alt="Logo">

tempDir()

Returns the path of the temporary directory with trailing slash. Provides the path to the system's temporary directory.

$path = Get::tempDir() . $file;

Date and Time Management

dateTimeZone()

Returns the current date and time based on configured timezone. Creates a DateTime object using the timezone settings from the configuration file.

$now = Get::dateTimeZone();
echo $now->format('Y-m-d H:i:s');

formatDate($date, $format = 'date', $timezone = false)

Formats a date based on the system settings. Converts a date string to the specified format according to system configuration.
$date: the date to format (in MySQL format) or DateTime object
$format: the format to use: 'date' (only date), 'time' (only time), or 'datetime' (both)
$timezone: optional timezone to convert the date to (e.g., 'Europe/Rome', 'America/New_York')

$formatted_date = Get::formatDate('2021-01-01', 'date');
$formatted_datetime = Get::formatDate('2021-01-01 14:30:00', 'datetime');

// Format date in user's timezone
$userTimezone = Get::userTimezone();
$formatted_user_date = Get::formatDate('2021-01-01 14:30:00', 'datetime', $userTimezone);

userTimezone()

Returns the current user's timezone identifier. The timezone is determined based on the following priority: explicitly set timezone using setUserTimezone(), authenticated user's timezone from their profile, or UTC as fallback. Requires use_user_timezone configuration to be enabled; otherwise always returns 'UTC'.

// Get current user's timezone
$timezone = Get::userTimezone();  // Returns 'Europe/Rome', 'America/New_York', or 'UTC'

// Use with formatDate to display dates in user's timezone
$displayDate = Get::formatDate($date, 'datetime', Get::userTimezone());

// Create DateTime in user's timezone
$now = new DateTime('now', new DateTimeZone(Get::userTimezone()));

setUserTimezone($timezone)

Explicitly sets the timezone for the current request. This overrides the authenticated user's timezone.

Locale Management

userLocale()

Returns the current user locale. It checks the explicitly set locale, then the authenticated user's locale, and falls back to the configured default.

$locale = Get::userLocale(); // e.g. 'it_IT'

setUserLocale($locale)

Explicitly sets the locale for the current request. This is used by formatDate() and other locale-aware helpers.

Get::setUserLocale('en_US');

Dependency Container

The dependency container system allows managing contractor classes, specifically designed to identify and manage classes within modules that are intended for external use. This facilitates integration between modules and enables a more modular and testable architecture.

bind($service_name, $implementation, $singleton = false, $arguments = [])

Registers a service in the dependency container. You can register a regular class, a singleton service, or a factory function. Registered services can then be instantiated using make().

// Register a regular class
Get::bind('database', DatabaseConnection::class);

// Register a singleton service
Get::bind('config', AppConfig::class, true);

// Register a factory function with initialization arguments
Get::bind('logger', function($filename) {
    return new FileLogger($filename);
}, false, ['app.log']);

make($name, $arguments = [])

Creates an instance of a registered service from the dependency container. Services must first be registered using the bind() method. This method is used together with bind() to manage module contractor classes.

// First register services
Get::bind('database', DatabaseConnection::class);
Get::bind('config', AppConfig::class, true);
Get::bind('logger', LoggerFactory::class);

has($name)

Checks if a service is registered in the dependency container.

if (Get::has('Auth')) {
    $auth = Get::make('Auth');
}

Client IP Management

clientIp($trust_proxy_headers = false)

Gets the client IP address. This method detects and returns the client's IP address, handling various scenarios including proxy headers and IPv6 to IPv4 conversion for localhost.

// Standard IP
$ip = Get::clientIp();

// IP considering proxy headers (useful with Cloudflare, load balancers, etc.)
$ip = Get::clientIp(true);
Loading...