Skip to content
← Back to Snippets
Code

Procedural Object-Data Pattern Without Classes

Builds a predictable associative-array record for object-like data while avoiding PHP class declarations.

Purpose

Builds a predictable associative-array record for object-like data while avoiding PHP class declarations.

Snippet details

ContextData PatternLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Procedural Object-Data Pattern Without Classes.
 *
 * Purpose:
 * Builds an object-like associative array with normalized fields and a clear
 * status value, without declaring or instantiating classes.
 *
 * @param array $input Raw record values.
 * @return array Normalized object-data record.
 */
function ogSnippetProceduralObjectDataPatternWithoutClasses(array $input): array {
	$record = array(
		'code' => '',
		'name' => '',
		'origin' => '',
		'status' => 'draft',
		'created_at' => gmdate('Y-m-d H:i:s')
	);

	if (isset($input['code']) === true) {
		$record['code'] = strtoupper(trim((string) $input['code']));
	}

	if (isset($input['name']) === true) {
		$record['name'] = trim((string) $input['name']);
	}

	if (isset($input['origin']) === true) {
		$record['origin'] = trim((string) $input['origin']);
	}

	if (isset($input['status']) === true) {
		$status = strtolower(trim((string) $input['status']));

		if ($status === 'draft' || $status === 'active' || $status === 'archived') {
			$record['status'] = $status;
		}
	}

	if ($record['code'] === '' || $record['name'] === '') {
		$record['status'] = 'draft';
	}

	return $record;
}

$ship_record = ogSnippetProceduralObjectDataPatternWithoutClasses(array(
	'code' => 'ncc-1701',
	'name' => 'USS Enterprise',
	'origin' => 'Star Trek',
	'status' => 'active'
));

echo 'Object-data record: '.$ship_record['code'].' '.$ship_record['name'];