I wrote this after repeatedly handling writing testable PHP functions on client projects. Testable PHP is not about frameworks only. I share how I write small functions that are easier to verify and refactor later.
Separate Logic From I/O
Testable PHP is not about frameworks only. I share how I write small functions that are easier to verify and refactor later.
- pure functions — applied directly to writing testable PHP functions.
- dependency injection basics — applied directly to writing testable PHP functions.
- input/output clarity — applied directly to writing testable PHP functions.
- edge cases — applied directly to writing testable PHP functions.
Putting It Together
When delivering Writing PHP Functions That Are Easy to Test, the build stayed focused on pure functions, dependency injection basics, input/output clarity, and edge cases. That restraint kept the release small enough to test properly before go-live.
Name Functions by Behavior
Representative code from the implementation — simplified for readability, but structurally what I deploy.
Cursor pagination for large MySQL tables
SELECT id, news_title, published_date
FROM news
WHERE status = 'Published' AND id < :cursor_id
ORDER BY id DESC
LIMIT 20;
CREATE INDEX idx_news_status_id ON news (status, id);Strict input validation at the service boundary
<?php
declare(strict_types=1);
final class RecordService
{
public function create(array $input): array
{
$title = trim($input['title'] ?? '');
if ($title === '' || strlen($title) > 180) {
throw new InvalidArgumentException('Invalid title.');
}
$stmt = $this->db->prepare('INSERT INTO records (title) VALUES (?)');
$stmt->bind_param('s', $title);
$stmt->execute();
return ['id' => $stmt->insert_id];
}
}After Shipping: What Actually Mattered
Once writing testable PHP functions was live, the team spent less time on rework because edge cases were handled at the boundary — not discovered in production.
The part worth copying is the scope discipline: solve the stated problem fully before adding adjacent nice-to-haves.
Before You Start Your Version
- Start with the exact problem statement for writing testable PHP functions — one sentence, no buzzwords.
- Prioritise pure functions before polishing secondary UI details.
- Validate dependency injection basics under realistic data volume, not demo rows.