Skip to content
Back to skills

Skill: Module Codebase (Perfex Module)

ASecurity

This skill provides guidelines, architectural patterns, templates, and scaffolding conventions for building high-quality, enterprise-grade Perfex CRM modules adhering to Clean Code standards, Perfex Core conventions, and modern software engineering best practices.

  • 25 stars
  • 0 votes
  • 0 copies
  • 20 views
  • Added February 7, 2026
developmentphpsqlvuenodetestingrefactoringapidatabasesecurityperformance

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 21 files and shows the line behind each finding

Scanned November 8, 2026

npx -y skills add PolyXGO/HeraSpec --skill module-codebase --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Skill: Module Codebase (Perfex Module)?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Skill: Module Codebase (Perfex Module)
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/polyxgo-skill-module-codebase-perfex-module/badge)](https://www.skillsdirectory.com/skills/polyxgo-skill-module-codebase-perfex-module)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
# Skill: Module Codebase & Clean Architecture (Perfex Module)

## Purpose

This skill provides guidelines, architectural patterns, templates, and scaffolding conventions for building high-quality, enterprise-grade Perfex CRM modules adhering to Clean Code standards, Perfex Core conventions, and modern software engineering best practices.

## When to Use

- When scaffolding a new module or refactoring an existing module.
- When structuring controllers, models, helpers, hooks, and views.
- When designing high-performance database schemas and composite indexes.
- When configuring asset bundling (Webpack), automated testing, and clean deployment packaging.

---

## Clean Code Architecture

### 1. Standard Module Directory Structure
```
modules/{module_name}/
├── {module_name}.php           # Main module bootstrap, registration & hooks
├── install.php                 # Schema migration & initial default options
├── uninstall.php               # Cleanup hooks (safe options removal / optional table drops)
├── package.json                # Build scripts (strictly excluded from production zip)
├── webpack.config.js           # Asset bundling config (strictly excluded from production zip)
├── deploy.ps1                  # Packaging script with strict /XD and /XF filters
├── assets/                     # Development source assets
│   ├── css/                    # Modular CSS stylesheets
│   └── js/                     # Modular JS scripts
│       ├── admin/              # Admin-specific modules
│       └── lib/                # Bundled offline libraries (Vue, SweetAlert2, etc.)
├── dist/                       # Minified production assets (enqueued in production)
│   └── assets/
│       ├── css/                # *.min.css
│       └── js/                 # *.min.js
├── controllers/                # Thin controllers (routing, permissions, input sanitization)
│   ├── {ModuleName}.php        # Admin page controller (extends AdminController)
│   └── Api.php                 # AJAX JSON endpoints (extends App_Controller / AdminController)
├── models/                     # Rich models (business logic, database queries, caching)
│   ├── {ModuleName}_model.php  # Core domain logic & query builder
│   └── {ModuleName}_settings_model.php # Settings, presets & option cache
├── helpers/                    # Utility helpers (static asset enqueuers, formatters)
│   └── {module_name}_helper.php
├── libraries/                  # Integration libraries & demo generators
├── views/                      # Pure HTML views (Zero inline JS/CSS)
│   └── admin/
├── language/                   # 100% Bilingual localization
│   ├── english/
│   │   └── {module_name}_lang.php
│   └── vietnamese/
│       └── {module_name}_lang.php
├── tests/                      # Automated test suite (strictly excluded from deploy)
│   └── Test_{ModuleName}.php
└── documentations/             # End-user documentation
    └── index.html              # Clean HTML guide (Zero inline style)
```

---

## Core Clean Code Principles

### 1. Thin Controllers, Rich Models (Separation of Concerns)
- **Controllers** should only:
  - Check permissions (`has_permission(...)`, `is_admin()`).
  - Validate and sanitize incoming HTTP input (`$this->input->post(...)`, `(int)$id`).
  - Release session lock if read-only (`session_write_close()`).
  - Delegate data processing to dedicated Models.
  - Return JSON or load view templates.
- **Models** should handle:
  - SQL Query Builder logic with automatic escaping.
  - Differential tracking and business rules.
  - Multi-channel notification dispatching.
  - High-performance caching.

### 2. High-Performance Database Indexing
For high-scale CRM entities (comments, mentions, activities, logs):
- Never rely solely on single-column primary keys for polymorphic queries.
- Add composite indexes on high-frequency filter pairs:
  ```sql
  KEY `idx_rel_lookup` (`rel_type`, `rel_id`),
  KEY `idx_user_inbox` (`target_type`, `target_id`, `is_read`, `date_created`)
  ```
- Always use `db_prefix() . '{module}_{table}'` for multi-tenant table prefix compatibility.
- Always specify character set and collation:
  ```sql
  ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ";
  ```

### 3. Centralized Asset Enqueuing & Fallback
In `{module_name}_helper.php`:
- Detect if minified `dist/` asset exists; fallback gracefully to `assets/` source if not built.
- Append file modification timestamp `?v={filemtime}` for zero-downtime client-side cache busting.
- Centralize JSON localization injection via `app_admin_head` so views contain zero inline scripts:
  ```php
  hooks()->add_action('app_admin_head', '{module_name}_inject_admin_head');
  ```

### 4. Client Portal Isolation Firewall
When extending modules to the Client Portal (`app_customers_head` / `app_customers_footer`):
- Never expose internal company staff, unassigned tickets, internal tasks, or confidential leads to clients.
- Filter lookups strictly to staff members assigned to the client's specific active projects or open tickets.
- Ensure all public visitor URLs fallback to safe placeholders (`#`) with no internal ID leakage.

### 5. PHP Concurrency & Session Lock Prevention
- Autocomplete, mention search, and read-only AJAX endpoints in Perfex CRM hold PHP session file locks by default.
- Always release the session lock at the start of read/search controller actions:
  ```php
  // Release PHP session file lock immediately for fast concurrent autocompleter queries
  session_write_close();
  ```

### 6. Test Isolation Rule (MANDATORY)
- All test scripts, benchmark runners, and verification scripts must be placed in `tests/` or `scratch/`.
- Never place test files in `controllers/` or `views/`.
- Ensure all packaging scripts (`deploy.ps1`, `deploy.sh`) strictly exclude `tests/` and `scratch/`.

---

## Step-by-Step Implementation Process

### Step 1: Requirements & Schema Analysis
1. Define entities and relationships (polymorphic relations to Perfex core tasks, projects, invoices, leads, tickets, clients).
2. Determine required hooks (`app_admin_head`, `app_admin_footer`, menu hooks, notification hooks).
3. Design database schema with composite indexes.

### Step 2: Scaffold Module Structure
- Run the scaffolding script from `scripts/` or use templates from `templates/`:
  - Main bootstrap: `{module_name}.php`
  - Installer: `install.php`
  - Uninstaller: `uninstall.php`
  - Helper: `helpers/{module_name}_helper.php`
  - Controller: `controllers/{ModuleName}.php` & `controllers/Api.php`
  - Model: `models/{ModuleName}_model.php`
  - Asset build system: `package.json`, `webpack.config.js`, `deploy.ps1`

### Step 3: Database & Options Migration (`install.php`)
- Check if table exists before creating:
  ```php
  if (!$CI->db->table_exists(db_prefix() . '{module_name}_table')) { ... }
  ```
- Register initial default settings via `add_option('{module_name}_default_option', 'value');`.

### Step 4: Thin Controllers & Concurrency Release
- In read-only search or autocomplete endpoints, call `session_write_close()` right after security checks.
- Always validate CSRF tokens on POST endpoints.

### Step 5: Pure Views (Zero Inline JS & CSS)
- Views must contain only semantic HTML and PHP loops/conditionals.
- Pass configuration via `data-*` attributes on wrapper container:
  ```html
  <div class="{module-name}-container" data-module="{module-name}" data-page="<?php echo html_escape($page_name); ?>">
  ```
- All styling in `assets/css/` and all logic in `assets/js/`.

### Step 6: Localization & Multilingual Parity
- Add all strings to `language/english/{module_name}_lang.php`.
- Mirror every key in `language/vietnamese/{module_name}_lang.php` (and any other supported language).
- 0 hardcoded English/Vietnamese strings in views or controllers.

### Step 7: Asset Minification & Clean Packaging
- Run `npm run build` to compile JS/CSS into `dist/assets/`.
- Verify tests pass in `tests/Test_{ModuleName}.php`.
- Run `deploy.ps1` to produce the clean production zip with all dev tooling excluded.

---

## Naming & Style Conventions

| Component | Convention | Example |
|---|---|---|
| Module Identifier | snake_case | `crosstag` |
| PHP Controller | PascalCase | `Crosstag.php`, `Api.php` |
| PHP Model | PascalCase with suffix | `Crosstag_model.php` |
| PHP Helper Class | snake_case with `_helper` | `crosstag_helper.php` |
| Language Keys | prefix with `{module}_` | `$lang['crosstag_col_bell']` |
| CSS Classes | prefix with `{module}-` | `.crosstag-user`, `.crosstag-finder` |
| Global JS Namespace | UPPER_SNAKE_CASE | `window.CROSSTAG_CONFIG` |
| JS Functions | camelCase | `extendTinyMCEStyles()`, `debounce()` |

---

## Available Templates

Located in `templates/`:
- `module-main.php` - Bootstrap `{module_name}.php` template with hooks and registration.
- `install.php` - Database schema, composite indexes, and initial options.
- `uninstall.php` - Clean uninstaller script.
- `controller-admin.php` - Thin admin controller template.
- `controller-api.php` - Fast AJAX JSON controller with `session_write_close()`.
- `model-main.php` - Rich model template with query builder.
- `helper.php` - Asset enqueuing helper with `dist/` fallback and `?v=` cache buster.
- `webpack.config.js` - Webpack 5 production bundling pipeline for JS & CSS.
- `package.json` - Build package config.
- `deploy.ps1` - Robocopy production packaging script with strict exclusions.

## Available Scripts

Located in `scripts/`:
- `scaffold-module.js` - Node.js CLI script to scaffold a complete Perfex module structure.

---

## Reference Implementation
- **CrossTag for Perfex** (`modules/crosstag/`): Production benchmark with dual-engine autocompleter, composite database indexes, asset fallback pipeline, and 57/57 passing automated test assertions.

Files in this skill

  • CHANGELOG.md3 KB
  • README-template.md1.4 KB
  • README.md1.8 KB
  • content-optimization-skill.md3 KB
  • data/charts.csv7.5 KB
  • data/colors.csv12.7 KB
  • data/landing.csv14.1 KB
  • data/pages-proposed.csv11.1 KB
  • data/pages.csv5 KB
  • data/products.csv29.1 KB
  • data/prompts.csv17 KB
  • data/stacks/flutter.csv10.2 KB
  • data/stacks/html-tailwind.csv11.1 KB
  • data/stacks/nextjs.csv12.3 KB
  • data/stacks/react-native.csv9.8 KB
  • data/stacks/react.csv12.7 KB
  • data/stacks/svelte.csv10.8 KB
  • data/stacks/swiftui.csv10.6 KB
  • data/stacks/vue.csv10.8 KB
  • data/styles.csv41 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.