MagratheaPHP2
Up to date Narrative last written —; no source changes since. Method signatures below are reflected live.

Admin Panel System

Files: src/Admin/Admin.php, src/Admin/AdminManager.php Namespace: Magrathea2\Admin

MagratheaPHP2 ships with a built-in admin panel system. It provides a configurable web UI for managing application data, users, configuration, cache, files, and API exploration. The admin panel is feature-based: you enable only what you need.


Quick Start

<?php
// admin/index.php
require_once __DIR__ . '/../vendor/autoload.php';

use Magrathea2\MagratheaPHP;
use Magrathea2\Admin\AdminManager;

MagratheaPHP::Instance()
    ->AppPath(__DIR__ . '/..')
    ->AddRootCodeFolder("models", "controls")
    ->Prod()
    ->Load()
    ->Connect()
    ->StartSession();

$manager = AdminManager::Instance()->StartDefault("My App Admin");

// Check authentication
if (!$manager->Auth()) {
    $manager->PermissionDenied();
    exit;
}

// Build the menu
$admin = $manager->GetAdmin();
$menu  = $admin->BuildMenu();

// Include the admin view
include $manager->GetAdmin()->GetViewPath("main.php");

Admin Class

File: src/Admin/Admin.php Implements: iAdmin

The primary configuration object for the admin panel. You configure the panel and then pass it to AdminManager::Start().

Properties

PropertyTypeDefaultDescription
$titlestring"Magrathea Admin"Panel title
$primaryColorstring"203, 128, 8"Primary color (RGB decimal)
$adminLogostringPath to logo image
$faviconstringPath to favicon
$extraMenuarrayExtra menu items
$adminFeaturesarrayRegistered admin features
$crudFeaturesarrayRegistered CRUD features

Configuration Methods

SetTitle(string $t): Admin

$admin->SetTitle("My App — Admin Panel");

SetPrimaryColor(string $color): Admin

Set primary color from a HEX value. Internally converts to RGB decimal.

$admin->SetPrimaryColor("#3A7BD5");

SetPrimaryColorDecimal(string $color): Admin

Set primary color as an RGB decimal string.

$admin->SetPrimaryColorDecimal("58, 123, 213");

SetLogo(string $logo): Admin / SetAdminLogo(string $logo): Admin

Set the logo image path.

$admin->SetLogo("/assets/logo.png");

AddFeaturesArray(array $arrFeatures): Admin

Register multiple features at once.

$admin->AddFeaturesArray([
    new UserFeature(),
    new ProductCrudFeature(),
]);

AddJs(string $filePath): Admin

Add a custom JavaScript file to the admin panel.

AddMenuItem(array ...$item): Admin

Add a custom menu item.

$admin->AddMenuItem([
    "label" => "Reports",
    "url"   => "/admin/reports",
    "icon"  => "chart-bar",
]);

BuildMenu(): AdminMenu

Build and return the menu structure.

Auth(AdminUser $user): bool

Validate admin authentication for a user.


AdminManager Class

File: src/Admin/AdminManager.php Extends: Singleton

The runtime manager for the admin panel. Handles initialization, authentication, JS/CSS compilation, and feature routing.

Starting the Admin

Start(Admin $admin): AdminManager

Initialize with a custom Admin configuration object.

$admin = new Admin();
$admin->SetTitle("My App")
      ->SetPrimaryColor("#e63946")
      ->AddFeaturesArray([...]);

AdminManager::Instance()->Start($admin);

StartDefault(?string $title = null, ?string $color = null): AdminManager

Start with default built-in features (user management, cache, config, file editor).

First-run setup

On every request, Start() decides what to show (Admin\Start::GetInstallState()):

The setup form's POST re-checks that there are still no users (Start::CanCreateFirstUser()) right before creating the account, so a setup page loaded earlier can't be replayed once a user exists. (Since 2.4.0. Before that, a missing admin_install_date row or any DB error showed the setup form to whoever opened the admin.)

AdminManager::Instance()->StartDefault("My App", "#e63946");

Built-in pages and actions

Once logged in, ?magrathea_page=<name> shows src/Admin/views/pages/<name>.php inside the admin layout, and ?magrathea_subpage=<name> runs src/Admin/views/actions/<name>.php alone (the AJAX actions). Only plain names of files that exist in those two folders are accepted (Admin\Start::GetViewFile()): anything else (../, sub-folders, a missing file) answers 404, "action not found" for an action and a "Page not found" alert for a page. Before 2.4.0 the name was concatenated into an include, so ../ reached any PHP file on the server. Your own pages belong in admin features (?magrathea_feature=), not in these folders.

Backups, logs, and the removed Query Tester

Authentication

Auth(): bool

Check if the current session has a valid admin user.

if (!AdminManager::Instance()->Auth()) {
    header("Location: /admin/login");
    exit;
}

GetLoggedUser(): AdminUser|null

Returns the currently logged-in admin user.

$user = AdminManager::Instance()->GetLoggedUser();
echo "Welcome, " . $user->name;

PermissionDenied(): void

Render a "permission denied" page.

ErrorPage(string $message): void

Render an error page with the given message.

UI Helpers

GetTitle(): string

Returns the panel title.

GetColor(): string

Returns the primary color as RGB decimal string.

PrintLogo(?int $logoSize = 200): void

Outputs the admin logo sized to $logoSize px — an <img> tag for .jpeg/.jpg/.png logos, or the inlined SVG markup for .svg logos.

GetFaviconTag(): string

Returns the favicon <link> HTML tag.

Feature Management

GetFeature(string $featureId): AdminFeature|null

Returns a registered feature by its ID.

$cacheFeature = AdminManager::Instance()->GetFeature("cache");

GetActiveFeature(): AdminFeature|null

Returns the feature matching the current URL segment.

Asset Management

AddJs(string $file): AdminManager

Add a JS file to the admin bundle.

GetJs(): string

Returns all bundled JS (minified).

GetJSManager(): JavascriptCompressor

Returns the underlying JS compressor instance.

AddCss(string $file): AdminManager

Add a CSS file to the admin bundle.

GetCss(): string

Returns all bundled CSS (minified/compiled).

GetCSSManager(): CssCompressor

Returns the underlying CSS compressor instance.

SetMenu(AdminMenu $m): AdminManager

Set the current menu.

GetMenu(): AdminMenu

Returns the current menu object.

Logging

Log(string $action, mixed $victim = null, mixed $data = null, mixed $user_id = false): void

Log an admin action.

AdminManager::Instance()->Log("deleted_product", $product->id, $product->ToArray());

Built-in Features

Admin::SetFeatures() (used by StartDefault(), and by any Admin subclass that calls parent::SetFeatures()) registers these features:

Feature IDDescription
AdminFeatureAppConfigDatabase-stored app configuration
AdminFeatureCacheCache management and clearing
AdminFeatureUserAdmin user management
AdminFeatureUserLogUser activity logs

Not registered by default, opt-in from your Admin subclass:

Feature IDDescriptionHow to enable
AdminFeatureFileEditorView/edit files on the server$this->LoadFileEditor() in SetFeatures() (see below)
ApiExplorerBrowse registered API endpointsnew ApiExplorer(), SetApi(...), AddFeature(...)

Enabling the File Editor

Since 2.4.0 the File Editor is off by default. Any logged-in admin user can use it to edit files on the server, so a leaked admin password becomes code execution. Enable it only where you actually need it:

class MyAppAdmin extends \Magrathea2\Admin\Admin implements \Magrathea2\Admin\iAdmin {
    public function SetFeatures() {
        parent::SetFeatures();
        $this->LoadFileEditor(); // or: $this->AddFeature(new \Magrathea2\Admin\Features\FileEditor\AdminFeatureFileEditor());
    }
}

When it's loaded, the Magrathea menu gets a "Tools → File Editor" entry, and the code generator's "File already exists" note links to the file. Without it, both are hidden, and a direct ?magrathea_feature=AdminFeatureFileEditor URL shows "Feature not available".

Objects and the code generator: "Strict types"

The object form (create an object from a table, or edit an existing one) has a Strict types select, saved as strict_types in the object's section of magrathea_objects.conf. When it's true, the generated Base class declares protected $strictTypes = true; (typed values on load, see "Strict typing" in the MagratheaModel docs); when it's false or missing, the line is left out and the model keeps the framework default (false).

Since 2.4.0, the select defaults to true for a new object. An existing object saved before 2.4.0 has no strict_types key: the form shows false for it, so re-saving or regenerating it doesn't change its Base class or its JSON. Turn it on deliberately, after checking the model's API consumers (numbers stop being strings in the JSON).

Code structure: feature or mvc

The "Generate Code" page sets where generated files go and their namespaces (App below is the configured namespace):

Filefeature (default)mvc
Modelfeatures/Product/Product.php, App\ProductModels/Product.php, App\Models
Model Basefeatures/Product/Base/ProductBase.php, App\Product\BaseModels/Base/ProductBase.php, App\Models\Base
Controlfeatures/Product/ProductControl.php, App\ProductControls/ProductControl.php, App\Controls
Control Basefeatures/Product/Base/ProductControlBase.php, App\Product\BaseControls/Base/ProductControlBase.php, App\Controls\Base
CRUD adminfeatures/Product/ProductAdmin.php, App\ProductControls/ProductAdmin.php, App\Controls
APIfeatures/Product/ProductApi.php, App\ProductControls/ProductApi.php, App\Controls

The generated CRUD admin and API classes use fully qualified model and control names, so they work in both structures. Before 2.4.0, the mvc CRUD admin, API and the Base model's GetControl() pointed at classes that don't exist.


Adding Custom CRUD Features

The most common admin customization is adding CRUD management for your models:

namespace App\Product;

use Magrathea2\Admin\Features\CrudObject\AdminCrudObject;

class ProductAdmin extends AdminCrudObject {
    public string $featureName = "Products";

    public function Initialize() {
        $this->SetObject(new Product()); // uses App\Product\ProductControl
    }
}
// in your Admin subclass's SetFeatures(), after parent::SetFeatures():
$this->AddCrudFeature(new \App\Product\ProductAdmin());

Without a second argument, SetObject() uses the control at <model class>Control, in the model's namespace. If the control lives elsewhere, pass it: $this->SetObject(new Product(), new ProductControl()). See the CRUD Object Feature in Admin Features for the details.


Notes

Class Reference — Admin

Magrathea2\Admin\Admin implements iAdmin /home/platypusweb/platypusweb.com.br/site/magratheaphp2/src/Admin/Admin.php

Class for managing Magrathea's Admin

AddFeaturesArray(array $arrFeatures): Magrathea2\Admin\Admin

Inserts an array of features.

ParamTypeDefault
$arrFeatures array required
AddFeaturesMenu(Magrathea2\Admin\AdminMenu $adminMenu): Magrathea2\Admin\AdminMenu

Adds menu items for all registered CRUD features.

ParamTypeDefault
$adminMenu Magrathea2\Admin\AdminMenu required
AddJs(string $filePath): Magrathea2\Admin\Admin

Add a JS file to the admin panel.

ParamTypeDefault
$filePath string required
AddMagratheaMenu(Magrathea2\Admin\AdminMenu $adminMenu): Magrathea2\Admin\AdminMenu

Adds the default Magrathea menu sections to the menu.

ParamTypeDefault
$adminMenu Magrathea2\Admin\AdminMenu required
AddMenuItem(array ...$item): Magrathea2\Admin\Admin

Adds one or more menu items to the extra menu.

ParamTypeDefault
$item array —
AddTests(): Magrathea2\Admin\Admin

Adds Magrathea's built-in tests to the test manager.

Auth($user): bool

Checks if a user has authorization to access the admin.

ParamTypeDefault
$user mixed required
BuildMenu(): Magrathea2\Admin\AdminMenu

Builds the admin menu.

GetFeatures()

Gets all registered admin features.

GetMenuItem(string $key): array

Gets the menu item for a specific feature.

ParamTypeDefault
$key string required
Initialize()

Initializes the admin, adding Magrathea tests.

SetFeatures()

Sets the default features for the admin panel.

SetPrimaryColor($color): Magrathea2\Admin\Admin

Sets the primary color from a hexadecimal value.

ParamTypeDefault
$color mixed required
SetPrimaryColorDecimal($color): Magrathea2\Admin\Admin

Sets the primary color from a decimal RGB string.

ParamTypeDefault
$color mixed required
SetTitle($t): Magrathea2\Admin\Admin

Sets title

ParamTypeDefault
$t mixed required
__construct()

Constructor. Adds the base javascript file for the admin panel.

Class Reference — AdminManager

Magrathea2\Admin\AdminManager extends Singleton /home/platypusweb/platypusweb.com.br/site/magratheaphp2/src/Admin/AdminManager.php

Class for managing Magrathea's Admin

AddCss($file): Magrathea2\Admin\AdminManager

Adds a css file to admin

ParamTypeDefault
$file mixed required
AddJs($file): Magrathea2\Admin\AdminManager

Adds a javascript file to admin

ParamTypeDefault
$file mixed required
Auth(): bool

Permission verification

ErrorPage($message)

display error page

ParamTypeDefault
$message mixed required
GetActiveFeature(): ?Magrathea2\Admin\AdminFeature

returns active feature (the one from "magrathea_feature" data)

GetAdmin(): ?Magrathea2\Admin\Admin

returns the current admin.

GetCSSManager(): Magrathea2\Compressors\CssCompressor

Gets CSS compressor

GetColor(): string

Gets color

GetCss(): string

Gets Js code

GetFaviconTag(): string
GetFeature($featureId): ?Magrathea2\Admin\AdminFeature

gets admin feature id and returns its object

ParamTypeDefault
$featureId mixed required
GetJSManager(): Magrathea2\Compressors\JavascriptCompressor

Gets Js compressor

GetJs(): string

Gets Js code

GetLoggedUser(): ?Magrathea2\Admin\Features\User\AdminUser

Return logged user

GetMenu(): Magrathea2\Admin\AdminMenu

Gets the AdminMenu

GetTitle(): string

Gets title

Initialize()
Log($action, $victim = null, $data = null, $user_id = false): void

Log an action

ParamTypeDefault
$action mixed required
$victim mixed null
$data mixed null
$user_id mixed false
PermissionDenied()

Show permission denied page

SetMenu(Magrathea2\Admin\AdminMenu $m): Magrathea2\Admin\AdminManager

Sets the menu

ParamTypeDefault
$m Magrathea2\Admin\AdminMenu required
Start(Magrathea2\Admin\Admin $admin): Magrathea2\Admin\AdminManager

Starts Admin

ParamTypeDefault
$admin Magrathea2\Admin\Admin required
StartDefault(?string $title = null, ?string $color = null): Magrathea2\Admin\AdminManager

Starts a default admin

ParamTypeDefault
$title ?string null
$color ?string null

Examples