Writing Functions & Classes

20+ production-ready prompt templates for generating functions, classes, APIs, and utilities. Copy, adapt, and use immediately.

Beginner 12 min read Lesson 7 of 20

Anatomy of a Great Prompt

Every strong code generation prompt has these elements:

Prompt anatomy
Write a [language] function called [name]([params]) that:
- [what it does - main purpose]
- [business rule 1]
- [business rule 2]
Returns: [what is returned on success]
Returns on error/failure: [what is returned when it fails]
[Optional: performance, style, or compatibility notes]
[Optional: example input/output]

Function Prompt Templates

Validation function
> Write a PHP function called validatePassword($password) that:
  - Checks minimum 8 characters
  - Requires at least one uppercase letter
  - Requires at least one number
  - Requires at least one special character (!@#$%^&*)
  - Returns true if valid
  - Returns an array of error strings if invalid (one message per failed rule)
  Include 5 test cases (2 valid, 3 invalid with different failures)
Database function
> Write a PHP function called getUsersWithPagination($pdo, $page, $perPage, $search = '') that:
  - Queries the users table (columns: id, name, email, role, created_at, is_active)
  - Filters by name or email if $search is not empty (use LIKE %search%)
  - Only returns active users (is_active = 1)
  - Paginates results using LIMIT and OFFSET
  - Returns ['data' => [...rows...], 'total' => int, 'pages' => int]
  - Uses PDO prepared statements
  - Handles the case where page is out of range (return empty data, not error)
File handling function
> Write a PHP function called uploadImage($file, $uploadDir, $maxSizeMB = 2) that:
  - Accepts a $_FILES['image'] array
  - Validates: file exists, type is JPG/PNG/WebP, size under $maxSizeMB MB
  - Generates a unique filename using uniqid + original extension
  - Moves file to $uploadDir
  - Returns ['success' => true, 'path' => 'uploads/abc123.jpg'] on success
  - Returns ['success' => false, 'error' => 'reason'] on failure
Python function
> Write a Python function called parse_invoice_pdf(pdf_path: str) -> dict that:
  - Reads a PDF file using PyMuPDF (fitz)
  - Extracts: invoice number, date, vendor name, total amount
  - Use regex to find these patterns in the text
  - Returns a dict with keys: invoice_number, date, vendor, total
  - Returns None if any field cannot be found
  - Include docstring and type hints

Class / Model Prompts

Full PHP model class
> Create a PHP class called ProductModel in /app/models/ProductModel.php:

Properties: $pdo (PDO connection)

Methods:
- __construct(PDO $pdo)
- findAll(array $filters = [], int $limit = 20, int $offset = 0): array
  Filters: category_id, min_price, max_price, is_active, search (name/description LIKE)
- findById(int $id): ?array
- create(array $data): int  -- returns new ID
- update(int $id, array $data): bool
- delete(int $id): bool  -- soft delete (set deleted_at timestamp)
- getByCategory(int $categoryId): array

Database: products table with columns:
  id, name, description, price, stock_qty, category_id, image_path, is_active, created_at, deleted_at

Rules:
- Use PDO prepared statements
- findAll must join with categories table to include category_name
- All methods must handle errors (return false/null on failure, not throw)
- Add PHPDoc to each public method
Python dataclass / service class
> Create a Python class called EmailService that:
  - Uses smtplib to send emails
  - __init__ takes: smtp_host, smtp_port, username, password
  - send_email(to: str, subject: str, html_body: str) -> bool
  - send_bulk(recipients: list[str], subject: str, html_body: str) -> dict
    Returns {'sent': 5, 'failed': 1, 'errors': [...]}
  - Handles connection errors gracefully (log + return False)
  - Include type hints and docstrings
  - Use a context manager for the SMTP connection

API Endpoint Prompts

REST API endpoint (PHP)
> Create a PHP REST API endpoint in /api/products.php that handles:

GET /api/products?page=1&limit=20&search=&category_id=
  Response: {"data": [...], "total": 100, "page": 1, "pages": 5}

POST /api/products
  Body: {name, description, price, category_id, stock_qty}
  Validates all required fields
  Response: {"success": true, "id": 42}

PUT /api/products/{id}
  Body: same as POST (partial update ok)
  Response: {"success": true}

DELETE /api/products/{id}
  Response: {"success": true}

Requirements:
- All responses are JSON with correct Content-Type header
- Auth via Bearer token in Authorization header (validate against sessions table)
- Use ProductModel class from /app/models/ProductModel.php
- Return {"error": "message"} with appropriate HTTP status on failure

Utility / Helper Prompts

Common utilities - copy any of these
# Date formatting:
> Write a PHP function formatRelativeTime($datetime) that returns
  strings like "2 hours ago", "3 days ago", "just now", "1 month ago"

# Slug generation:
> Write a PHP function generateSlug($title) that converts
  "Hello World! This is a Test" to "hello-world-this-is-a-test"
  Handle: spaces, special chars, duplicate slugs (add -1, -2 suffix)
  Accept optional $pdo to check uniqueness in a slugs column

# Currency formatting:
> Write a PHP function formatINR($amount) that formats
  1234567.89 as "₹12,34,567.89" using Indian number formatting

# CSV export:
> Write a PHP function exportToCSV(array $data, string $filename) that:
  - Sets headers for CSV download
  - Uses the array keys of the first row as column headers
  - Handles special chars (commas, quotes) correctly in cell values

# Recursive tree builder:
> Write a PHP function buildTree(array $flat, $parentId = null) that:
  - Takes a flat array of items with 'id' and 'parent_id' fields
  - Returns a nested array (each item has a 'children' key)
  - Used for categories, menus, comments

Quality Booster Phrases

Add these to any prompt to improve output quality:

Add this phraseWhat it does
"Include 5 test cases"Forces AI to verify its own logic
"Add PHPDoc / JSDoc comments"Gets documented output
"Handle all error cases"Forces error handling inclusion
"Use PDO prepared statements"Prevents SQL injection
"Match the style of [ClassName]"Consistent code style
"Explain your approach briefly"Gets rationale for choices
"PHP 8.2 only - use named arguments and match expressions"Modern language features
"Return null on failure, not false or exceptions"Consistent error contract

Frequently Asked Questions

Specify: input parameters (name and type), return value (what it returns, what it returns on error/failure), business rules (validation rules, constraints), and any performance requirements (must handle 10,000 records). The more you specify, the less you will need to iterate. For simple utilities, a one-line description is enough.

For a new class: ask for the full class structure first (properties, method signatures, constructor) without implementation. Review the structure, then ask for each method body separately. This two-step approach catches architectural issues early before they are baked into implementation.

Add style instructions to your prompt or CLAUDE.md: "Use camelCase for method names", "Add PHPDoc blocks for all public methods", "No inline comments", "Return arrays not objects". Alternatively: "Match the style of the UserModel class" and let the AI read it for reference.