Coding Standards

CMD Pro Coding Standards

Writing Clean, Consistent, and Secure Code
๐Ÿ“… Last Updated: August 2026 โฑ๏ธ Reading Time: 12 minutes ๐Ÿ“‹ Version: 2.1
The CMD Pro coding standards establish a consistent, high-quality, and maintainable codebase that adheres to industry best practices and WordPress community guidelines. These standards ensure that the plugin is secure, performant, scalable, and easily maintainable by multiple developers over its lifecycle. All code contributions must comply with these standards.

18.1. Coding Standards Overview

๐Ÿ˜ PHP Standards WordPress Coding Standards (primary), PSR-12 principles (where compatible), PHP 8.x+, Namespace usage, OOP patterns
๐Ÿ“œ JavaScript Standards ES6+, jQuery only when required, Chart.js usage, Fetch API, Async/Await
๐Ÿ”Œ API & AJAX Standards REST API design, WordPress REST API standards, Admin AJAX (admin only), Fetch API, Nonce verification
๐Ÿ”’ Security Best Practices Input validation, Output escaping, Nonce verification, Capability checks, SQL preparation, External API security, Secrets management
๐Ÿ› ๏ธ Code Quality Tools PHP CodeSniffer, PHPStan, ESLint, Prettier, Composer, NPM
๐Ÿ“‹ Development Workflow Git branching, Commit messages, Code review, CI/CD, Testing
๐Ÿ“Š

Coding Standards at a Glance

2 PHP Standards
8+ PHP 8.x Features
8 Security Rules
6 Quality Tools
6 OOP Patterns
โณ jQuery only when required

18.2. PHP Coding Standards

๐Ÿ“Œ Primary Standard: CMD Pro follows WordPress Coding Standards as the primary standard for WordPress-specific code. PSR-12 principles are applied where they do not conflict with WordPress conventions. When conflicts arise, WordPress Coding Standards take precedence.

18.2.1. PHP & PSR-12 Guidelines

Rule Requirement Example
File Header Docblock with file description, author, copyright <?php
/**
* CMD Pro - Commodity Dashboard
* ...
*/
Namespace Declare namespace for all classes namespace CMD_Pro\Admin;
Class Declaration Class name in StudlyCaps class PriceManager {
Method Declaration Method name in camelCase public function getLatestPrice() {
Constants Constant names in UPPER_SNAKE_CASE const MAX_RETRY_ATTEMPTS = 3;
Indentation Tabs (WordPress standard) $price = $this->fetchData(); // tab indentation
Visibility Explicit public, protected, private private $price;
Type Declarations Use type hints for parameters and return types public function getPrice(): float {
PSR-12 Compatibility Apply PSR-12 principles where they do not conflict with WordPress standards 4-space indentation is not required; tabs are preferred per WordPress

18.2.2. WordPress Coding Standards

Rule Requirement Example
Prefixing Prefix all functions, classes, hooks with cmdp_ or CMD_Pro function cmdp_get_prices()
Internationalization All text strings must be internationalized esc_html__('Price', 'cmd-pro')
Naming Conventions Lowercase and underscores for functions and hooks cmdp_update_price()
SQL Queries Use $wpdb->prepare() for all SQL queries $wpdb->prepare("SELECT * FROM $table WHERE id = %d", $id)
Output Escaping Use appropriate escaping functions esc_html(), esc_attr(), esc_url()
Capability Checks Verify user capabilities before actions if (!current_user_can('manage_options'))
Nonce Verification Use WordPress nonces for security check_admin_referer('cmdp_action', 'cmdp_nonce')

18.2.3. PHP 8.x Compatibility

Feature Requirement Example
Type Declarations Use int, float, string, bool, array, object function processPrice(float $price): array {
Null Safety Use null coalescing and null safe operators $price = $data['price'] ?? 0.00;
$value = $object?->getPrice();
Match Expression Use match for complex conditionals $action = match($type) {
'above' => 'alert_above',
'below' => 'alert_below',
};
Constructor Promotion Constructor property promotion (PHP 8.0+) public function __construct(
private float $price,
private string $commodity
) { }
Attributes May be used for internal metadata where appropriate;
Do not replace WordPress hooks or REST route registration
Internal class metadata, service tagging
Union Types Use union types for multiple type support public function formatPrice(float|int $price): string {
Minimum Version Requires PHP 8.1 or higher Production compatibility matrix to be finalized before release

18.2.4. OOP Patterns

๐Ÿ”’ Singleton Use sparingly for genuinely global plugin services; prefer dependency injection where practical
๐Ÿญ Factory For creating objects without specifying concrete classes
๐Ÿ”„ Strategy For interchangeable algorithms (API providers)
๐Ÿ‘€ Observer For alert notifications and event handling
๐Ÿ’‰ Dependency Injection For decoupling classes; recommended over Singleton for testability
๐Ÿ“ฆ Repository For data access abstraction

18.3. JavaScript Coding Standards

18.3.1. Modern JavaScript (ES6+)

Feature Requirement Example
Variable Declaration Use const and let; never var const prices = [];
let total = 0;
Arrow Functions Use arrow functions for callbacks fetchData().then(data => { ... });
Template Literals Use template literals for string concatenation const message = `${commodity} price: ${price}`;
Destructuring Use destructuring for cleaner code const { price, commodity } = response.data;
Spread Operator Use spread operator for arrays and objects const newPrices = [...oldPrices, newPrice];
Async/Await Prefer async/await over raw promises async function getPrice() {
const data = await fetch('/api/price');
}
Classes Use ES6 class syntax class PriceManager {
constructor() { ... }
}

18.3.2. jQuery Usage Policy

โœ… Preferred: Vanilla JavaScript

  • DOM Manipulation: document.querySelector(), element.classList.add()
  • Event Handling: element.addEventListener()
  • AJAX Calls: fetch() API
  • Element Selection: document.querySelectorAll()

Exception: jQuery may be used when required by WordPress core integration or when it significantly reduces code complexity. Always prefer vanilla JavaScript for new code.

18.3.3. Chart.js Usage

Development: CDN may be used for prototyping and development Production: Bundle the approved Chart.js version with CMD Pro and enqueue the local asset through WordPress Responsive: options: { responsive: true, maintainAspectRatio: false } Color Scheme: borderColor: '#2563EB', backgroundColor: 'rgba(37, 99, 235, 0.1)' Destroy: if (window.priceChart) { window.priceChart.destroy(); }
Why bundle Chart.js? Predictable version, no external CDN dependency, better privacy, easier CSP configuration, controlled testing, avoids CDN serving newer incompatible versions.

18.4. API & AJAX Standards

๐Ÿ“Œ Architecture Guidance: REST API should be preferred for CMD Pro dashboard/API functionality. Admin AJAX should be reserved for WordPress-admin-specific operations where it is appropriate.

18.4.1. WordPress REST API

Rule Requirement Example
Namespace Use cmd-pro/v1 or cmd-pro/v2 register_rest_route('cmd-pro/v1', '/price', ...)
Endpoint Naming Descriptive, lowercase, hyphen-separated /cmd-pro/v1/price, /cmd-pro/v1/history
HTTP Methods Use appropriate HTTP methods GET – Read, POST – Create, PUT – Update, DELETE – Delete
Authentication Use appropriate WordPress authentication mechanisms; use REST nonces for authenticated browser requests where applicable X-WP-Nonce header or _wpnonce parameter
Permissions Implement permission callbacks permission_callback: function($request) {
return current_user_can('read');
}
Response Format Return JSON with consistent structure return rest_ensure_response([
'success' => true,
'data' => $data
]);

18.4.2. AJAX Standards

Rule Requirement Example
Admin AJAX Use WordPress admin AJAX for admin-specific operations admin_url('admin-ajax.php')
Action Prefix Prefix AJAX actions with plugin prefix cmdp_update_price
Nonce Verification Always verify nonce for security check_ajax_referer('cmdp_nonce', 'nonce');
Response Format Return JSON with consistent structure wp_send_json_success(['price' => $price]);

18.5. Security Best Practices

โœ… Input Validation Validate all user inputs using WordPress validation functions
โœ… Input Sanitization Sanitize all inputs using sanitize_text_field(), sanitize_email()
โœ… Output Escaping Escape all outputs using esc_html(), esc_url(), esc_attr()
โœ… Nonce Verification Verify nonces for all forms using check_admin_referer()
โœ… Capability Checks Check capabilities using current_user_can() before actions
โœ… SQL Preparation Use $wpdb->prepare() for all database queries
๐ŸŒ External API Security Use WordPress HTTP API (wp_remote_get()), validate responses, enforce timeouts, and never expose private API keys to frontend JavaScript
๐Ÿ” Secrets & Credentials API keys must never be hard-coded in JavaScript, public repositories, HTML output, or REST responses

18.6. Code Quality Tools

๐Ÿ” PHP CodeSniffer PHP coding standards enforcement
๐Ÿ“Š PHPStan Static analysis for PHP
๐Ÿ“œ ESLint JavaScript linting
โœจ Prettier JavaScript formatting
๐Ÿ“ฆ Composer PHP dependency management
๐Ÿ“ฆ NPM JavaScript dependency management

18.7. Development Workflow

๐Ÿ”„ DEVELOPMENT WORKFLOW
๐ŸŒฟ Branch
โ†’
โœ๏ธ Write Code
โ†’
๐Ÿ” Run Quality Tools
โ†’
๐Ÿงช Write Tests
โ†’
โœ… Run Tests
๐Ÿ“ Commit
โ†’
๐Ÿ“ค Push
โ†’
๐Ÿ“‹ Pull Request
โ†’
๐Ÿ‘€ Code Review
โ†’
โœ… Merge

18.7.1. Git Commit Standards

Rule Requirement Example
Commit Message Format Use conventional commits feat: Add price alert system
fix: Correct USD to PKR conversion
docs: Update installation instructions
Type Tags Use type prefixes feat:, fix:, docs:, style:, refactor:, test:, chore:
Scope Tags Include scope in parentheses feat(api): Add Alpha Vantage provider
fix(database): Correct table schema
Branch Naming Use descriptive branch names feature/price-alerts
fix/currency-conversion
chore/update-dependencies

18.8. Pre-Merge Coding Checklist

๐Ÿ“‹ Required before merge/release: All items in this checklist must be verified before any code is merged into the main branch.
โฌœ PSR-12 compatible (where applicable)
โฌœ WordPress Coding Standards
โฌœ PHP 8.x compatible (minimum 8.1)
โฌœ Namespace usage
โฌœ OOP patterns applied appropriately
โฌœ ES6+ syntax (no var)
โฌœ No unnecessary jQuery
โฌœ Chart.js bundled locally
โฌœ REST API standards followed
โฌœ AJAX using fetch API or WordPress REST
โฌœ Input validation
โฌœ Output escaping
โฌœ Nonce verification
โฌœ Capability checks
โฌœ SQL preparation ($wpdb->prepare())
โฌœ External API security
โฌœ Secrets management (no hard-coded keys)
โฌœ Prefer WordPress APIs over raw $wpdb
โฌœ File headers
โฌœ Class docblocks
โฌœ Method docblocks
โฌœ Unit tests written
โฌœ Tests pass
๐Ÿ› ๏ธ

Coding Standards Conclusion

These Coding Standards establish a consistent, high-quality, and maintainable codebase for CMD Pro. By adhering to WordPress Coding Standards (primary), PSR-12 principles (where compatible), and PHP 8.1+ best practices, the codebase ensures security, performance, and scalability. All contributions must comply with these standards to maintain the integrity and reliability of the plugin.

Next โžก
โœ… Document Status: Approved for Development ๐Ÿ“‹ Standards Version: 2.1 ๐Ÿ“… Last Updated: August 2026
Don`t copy text!
Scroll to Top