انتقل إلى المحتوى

Architecture & Developer Setup Guide

Comprehensive technical guide covering the system architecture, 11-layer content contract, database self-healing & transaction safety, subfolder routing mechanics, and Swiss Flat design system rules for TidyFactor-Go maintainers and developers.


1. System Architecture Overview

TidyFactor-Go combines a lightweight FlightPHP API Gateway with a React 19 single-page application.

┌─────────────────────────────────────────────────────────┐
│                    React 19 Frontend                    │
│  (AppRouter, Tailwind CSS 4, Framer Motion, i18next)    │
└───────────────────────────┬─────────────────────────────┘
                            │ API Calls via resolveApiUrl()
┌───────────────────────────▼─────────────────────────────┐
│                 FlightPHP Backend Gateway               │
│  (ContentService, AdminAuth, Config, Http CachePolicy)  │
└───────────────────────────┬─────────────────────────────┘
                            │ PDO Transactions & WAL Mode
┌───────────────────────────▼─────────────────────────────┐
│                 SQLite Database Engine                  │
│  (database.sqlite auto-healed from baseline database)   │
└─────────────────────────────────────────────────────────┘

2. The 11-Layer Schema & Content Persistence Protocol

All persistent CMS content is stored as unified JSON documents inside SQLite. Any modification or addition of CMS sections must maintain compatibility across all 11 architecture layers in strict order:

  1. Types Layer (src/content/types.ts): Add data interfaces, add key to ManagedSiteContent, extend seo page union.
  2. Defaults Layer (src/content/defaultContent.ts): Add fallback data block, default SEO meta, and nav links in header.navLinks and footer.quickLinks.
  3. Router Basename Registry (index.html): Add route path (e.g. '/pricing') to routes array in the inline base detection script.
  4. Backend Schema & Self-Healing (backend/cms-api/src/Service/ContentService.php):
  5. Add key to $requiredFields in validateSchema().
  6. Add default PHP array constant and auto-inject in getContent() (read) and updateContent() (write).
  7. Add route slug to detectChanges() array and seo loop.
  8. Admin Client Validator & Navigation (src/pages/admin/AdminPage.tsx):
  9. Add key to requiredKeys in handleApplyRawJson().
  10. Add section item to sidebar navigation list.
  11. Render section form workspace (<NewPageSectionForm />).
  12. Admin Form Workspace (src/pages/admin/NewPageSectionForm.tsx): Build workspace form using inline FieldRow elements and Content / Settings / SEO tabs.
  13. Public Page Component (src/pages/NewPage.tsx): Build component using useContent(), getLocalizedText(), and isEnabled(). Avoid using whileInView for hero/card opacity animations to prevent Framer Motion transition lockups.
  14. App Router (src/routes/AppRouter.tsx): Register route inside <MainLayout> block (<Route path="new-page" element={<NewPage />} />). Do NOT wrap <Routes> with custom location-checking components.
  15. SEO & Path Mapping (src/App.tsx & src/lib/usePageSeo.ts): Register path slug mapping in getPageKey() and SEO_PAGE_BY_PATH. Use optional chaining (content?.seo?.[key]) for failsafe metadata resolution.
  16. Sitemap Generator (backend/cms-api/routes/content.php): Add path slug to $pages array in /api/sitemap.xml.
  17. Database Seeding (database.sqlite & database-baseline.sqlite): Update active database and baseline installer template using PHP seed script.

3. Critical Engine & Environment Rules

FlightPHP Engine Binding Rule

In backend/cms-api/public/index.php, custom engine initialization must always bind the global instance:

$app = new Engine();
Flight::setEngine($app);
Never omit Flight::setEngine($app). If omitted, static helper calls (like Flight::json()) write response bodies onto a separate, unused global Engine instance, causing empty responses.

Custom .env Loader (loadEnvFile())

PHP built-in development server (php -S) does not parse .env files automatically. The engine parses environment files line-by-line using:

putenv("{$key}={$value}");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;


4. Database Storage & Transaction Safety

All data resides in backend/cms-api/storage/database.sqlite: - WAL Journal Mode: Configured with Write-Ahead Logging (DB_JOURNAL_MODE="wal") to allow non-blocking concurrent reads during write transactions. - Busy Timeout: 5000ms busy timeout configured on PDO connections. - Automatic Backup Rotation: On content save, an automatic snapshot is created in content_backups and rotated to preserve up to 10 max backups (BACKUP_MAX_COUNT). - Inquiry Record Cap: Contact lead entries in inquiries are capped at 200 records maximum (FIFO automatic pruning) to prevent disk space starvation. - Baseline DB Self-Healing: Both SqliteConnection.php and install/index.php automatically restore missing database files from database-baseline.sqlite.


5. Subfolder API Resolution & Cache Policy

To ensure 100% deployment portability without hardcoded depth assumptions:

  • Frontend API Calls: Wrapped using resolveApiUrl('api/...') from src/lib/apiUrl.ts. Automatically calculates relative base depth regardless of subfolder path depth (/demos/TidyFactor-Go/).
  • HTTP Cache Policies (Http::setCachePolicy):
  • live: no-store (Cache-Control: no-store, no-cache, must-revalidate, max-age=0) for real-time authentication and admin endpoints.
  • dynamic: no-cache (Cache-Control: no-cache) for semi-dynamic content endpoints (/api/content/site).
  • static: public max-age caching (Cache-Control: public, max-age=3600, s-maxage=86400) for static sitemap and media assets.

6. Swiss Flat Design System

The platform strictly follows Swiss Flat UI aesthetics:

  • Color Palette:
  • Primary Blue: #0A2540
  • Accent Red: #D62828
  • Brand Depth: #081C30
  • Border Line: var(--border) (1px crisp dividing lines border-border)
  • Typography:
  • English / Primary Sans: Inter
  • Arabic Sans: Cairo (Optimized RTL line lengths & symmetry)
  • Layout & Sizing:
  • Compact container padding (py-16 to py-24).
  • Soft-corner buttons (rounded-sm).
  • Bento grid cards with split workspace inspector sidebars.
  • Abstract Business Decoupling:
  • Interface text & fallbacks must use Abstract Business Concepts ("Performance", "Efficiency", "Global Compliance") rather than hardcoded specific verticals, enabling seamless multi-industry deployment.

7. Local Development & Bootstrap

Prerequisites

  • PHP >= 8.1 with PDO SQLite extension
  • Node.js >= 18
  • Composer & npm

Setup Steps

  1. Initialize Backend:
    cd backend/cms-api
    php -S localhost:8000 -t public
    
  2. Initialize Frontend:
    npm install
    npm run dev
    
  3. Verify Build & Typecheck:
    npm run lint # Runs npx tsc --noEmit
    npm run build