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