AB-Socks Code Quality & Refactoring

VerifiedSafe

Playbook for safely refactoring bloated PHP controllers, extracting business logic into domain services, and decomposing views, with size thresholds and a verifier.

Sby Skills Guide Bot
DevelopmentIntermediate
11/3/2026
Claude Code
#php#refactoring#code-quality#mvc#technical-debt

Recommended for

Automated summary

Provides a step-by-step protocol and guardrails for refactoring bloated PHP controllers and views and paying down technical debt in the AB-Socks project.

Strengths

  • Sets concrete thresholds (controllers target under 80 lines, hard limit at 120) and clear responsibilities for each layer.
  • Offers an operational sequence: baseline with tools/verify.php, concern separation, service extraction, a thin orchestrating controller, then view decomposition.
  • Includes a service-function contract covering validation, CSRF, prepared statements, and transaction advice for sensitive operations.
  • Reinforces separation and security rules: no SQL in controllers or views, escaping through e().

Limitations

  • Tightly coupled to AB-Socks: project-specific paths, global-function PHP conventions, Persian messages, and the tools/verify.php tool.
  • The provided text cuts off in the middle of the partials section, so that guidance is incomplete.
  • Does not cover regression tests, rollback strategy, or success metrics beyond the verifier.
When to use it

Use it when shrinking an oversized PHP controller or view in AB-Socks or addressing an architectural warning from tools/verify.php.

When not to use it

Avoid it for PHP projects that do not follow AB-Socks architecture, conventions, and tooling, or when refactoring should wait for missing test coverage.

Security analysis

Safe
Quality score88/100

This is a refactoring playbook containing architectural guidance and illustrative PHP snippets. It does not instruct destructive commands, obfuscated execution, credential exfiltration, or safety bypasses. References to running a local verifier and using SQL/CSRF protections are legitimate development practices, and no tools are declared for execution.

No concerns found

How this analysis is made

Examples

Extract controller logic
Refactor app/controllers/product_edit.php. It is over 150 lines and contains SQL. Extract the validation and database work into the appropriate service under app/services/, keep the controller as a thin orchestrator under 80 lines, then run php tools/verify.php and report any remaining warnings.
Split a large view
views/admin/appearance.php is around 350 lines with repeated form sections. Decompose it into partials under views/admin/partials/, remove any direct db() calls or $_POST handling, and show me the updated view structure.
Resolve verifier violation
tools/verify.php flags SQL queries in a controller and form handling in a view. Walk through the AB-Socks refactoring protocol to move that logic into a service function using the standard ['ok' => bool, 'error' => string] return contract.

name: ab-socks-refactor description: > Protocol and playbook for refactoring bloated controllers, tangled views, and paying down technical debt in the AB-Socks project. Use this skill whenever refactoring a file, breaking down a controller exceeding line limits (>80-120 lines), extracting business logic into services, decomposing views into partials, or when tools/verify.php flags architectural violations.

AB-Socks Code Quality & Refactoring Playbook

This skill provides step-by-step guidance for safely decomposing bloated files, extracting domain services, and keeping the codebase maintainable and extensible.


1. Architectural Guardrails & Thresholds

| Component | Target Size | Hard Limit | Rules | |---|---|---|---| | Controller (app/controllers/) | < 80 lines | 120 lines | Zero SQL queries, zero calculation logic. Only parses $_GET/$_POST, calls a service, passes variables to renderView(). | | View (views/) | Modular | N/A | Zero database queries (db()), zero form handling ($_POST). Only loops, conditions, and e() escaping. | | Service (app/services/) | Focused | N/A | All SQL queries, business logic, calculations, and validations live here as plain global functions returning ['ok' => bool, 'error' => string]. | | Core Helper (app/core/) | Domain-agnostic | N/A | Formatting, slug generation, general helpers. No direct order/product business logic. |


2. Refactoring Protocol (Step-by-Step)

When refactoring a legacy or bloated controller (e.g. appearance.php, product_edit.php, settings.php):

Step 1: Establish Baseline

Run the verifier to see current errors/warnings:

php tools/verify.php

Step 2: Identify Concerns

Break the controller down into 3 distinct parts:

  1. Input handling & state: What does it read from $_GET, $_POST, or $_SESSION?
  2. Business logic & DB writes: What validation, SQL queries, or data transformations are happening?
  3. View payload: What variables are actually passed into renderView()?

Step 3: Extract Domain Service Function

Move all DB queries, validation, and calculations into the appropriate service in app/services/ (or create a new service if a new domain concern).

Service Function Contract:

/**
 * Saves or updates an entity from form input.
 *
 * @param array $input Raw form data (sanitized inside service)
 * @param int $id Record ID (0 for new)
 * @return array ['ok' => bool, 'error' => string|null, 'id' => int|null]
 */
function saveEntityFromRequest(array $input, int $id = 0): array {
    verifyCsrf();
    
    // 1. Validate
    $errors = validateEntityInput($input);
    if (!empty($errors)) {
        return ['ok' => false, 'error' => implode(' ', $errors)];
    }
    
    // 2. Perform DB operations with prepared statements
    $db = db();
    // Use transaction if touching stock, money, or multiple tables!
    // ...
    
    return ['ok' => true, 'id' => $id ?: (int) $db->lastInsertId()];
}

Step 4: Streamline the Controller

The controller should now be a clean orchestrator (typically 30–60 lines):

<?php
$id = (int) ($_GET['id'] ?? 0);
$entity = $id ? getEntityById($id) : null;
if ($id && !$entity) redirect('admin/entities.php');

$error = null;
$success = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = saveEntityFromRequest($_POST, $id);
    if ($result['ok']) {
        setFlash('success', 'تغییرات با موفقیت ذخیره شد.');
        redirect('admin/entities.php');
    } else {
        $error = $result['error'];
    }
}

$pageTitle = $id ? 'ویرایش آیتم' : 'افزودن آیتم';
renderView('admin/entity_edit', compact('pageTitle', 'entity', 'error', 'success'));

Step 5: Decompose Heavy Views into Partials

If a view has grown past 200–300 lines or contains repetitive UI (like cards, tabs, form sections):

  1. Extract subsections into views/admin/partials/ or views/site/partials/.
  2. Include them via standard PHP:
    <?php require __DIR__ . '/partials/entity_tab_general.php'; ?>
    
  3. Ensure no partial performs database queries or mutates state.

Step 6: Eliminate Inline Scripts & Deduplicate Front-End Logic

  1. Never write new duplicate JS helpers: Check docs/COMPONENTS.md for existing toast, modal, formatter, autocomplete, and image compression tools.
  2. Eliminate inline <script>: Move interactive behaviors to declarative data-ab-* attributes or dedicated external JS files. Keep inline scripts under 20 lines.
  3. Use unified design tokens: Never declare page-specific :root palettes or raw hex colors in component CSS.

3. Safe Refactoring Checklist

  • [ ] php tools/verify.php passes with 0 errors and adheres to the ratchet baseline.
  • [ ] No controller exceeds 120 lines (aim for < 80).
  • [ ] No SQL queries exist in any touched view.
  • [ ] No DB writes exist directly in any touched controller.
  • [ ] Zero duplicate JS helpers introduced (consult docs/COMPONENTS.md).
  • [ ] No inline <script> tags exceed 20 lines in touched views.
  • [ ] CSS uses unified :root variables without redundant palette declarations.
  • [ ] Transaction and row locking (FOR UPDATE) preserved if money/stock is involved.
  • [ ] CSRF verification retained on all POST operations.
  • [ ] Persian UI text and English comments preserved.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/ab-socks-code-quality-refactoring-mvg6txfl/download' --output '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md.part' && mv '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md.part' '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md' && test -s '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/ab-socks-refactor' && cp -R '.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl' '.claude/skills/ab-socks-refactor'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl'

openskills read 'ab-socks-code-quality-refactoring-mvg6txfl'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/ab-socks-code-quality-refactoring-mvg6txfl/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills