Skip to content

Instantly share code, notes, and snippets.

@manchumahara
Created January 9, 2025 10:56
Show Gist options
  • Save manchumahara/cae94790c8cd744db848d2fdf1a222ac to your computer and use it in GitHub Desktop.
Save manchumahara/cae94790c8cd744db848d2fdf1a222ac to your computer and use it in GitHub Desktop.
Use a table field as array - php + wordpress
<?php
class TableDateFieldAsArray {
private $postId; // The post ID for context
private $primaryKey; // Primary key for rows
private $tableName; // Custom table name
private $fieldName; // Field in the table to store serialized data
private $data = []; // The actual data
private $nextIndex = 1;
private $usedKeys = []; // Track all used keys
private $wpdb; // WordPress database object
public function __construct( $postId, $tableName, $fieldName, $primaryKey = 'id' ) {
global $wpdb;
$this->postId = $postId;
$this->primaryKey = $primaryKey;
$this->tableName = $tableName; // Custom table name
$this->fieldName = $fieldName; // Field name to store serialized data
$this->wpdb = $wpdb; // Access the global $wpdb object
$this->loadData();
}
// Load data from the custom table
private function loadData() {
$query = $this->wpdb->prepare(
"SELECT {$this->fieldName} FROM {$this->tableName} WHERE post_id = %d",
$this->postId
);
$result = $this->wpdb->get_var( $query );
if ( $result ) {
$decodedData = maybe_unserialize( $result );
if ( is_array( $decodedData ) ) {
$this->data = $decodedData['data'] ?? [];
$this->nextIndex = $decodedData['nextIndex'] ?? 1;
$this->usedKeys = $decodedData['usedKeys'] ?? [];
}
}
}
// Save data to the custom table
private function saveData() {
$serializedData = maybe_serialize( [
'data' => $this->data,
'nextIndex' => $this->nextIndex,
'usedKeys' => $this->usedKeys,
] );
$this->wpdb->replace(
$this->tableName,
[
'post_id' => $this->postId,
$this->fieldName => $serializedData,
],
[
'%d',
'%s',
]
);
}
// Insert a new row
public function insert( $row ) {
$primaryKey = $this->primaryKey;
if ( ! isset( $row[ $primaryKey ] ) ) {
$row[ $primaryKey ] = $this->nextIndex;
$this->nextIndex++;
} else {
foreach ( $this->data as $dataRow ) {
if ( $dataRow[ $primaryKey ] === $row[ $primaryKey ] ) {
throw new InvalidArgumentException( "Primary key {$row[$primaryKey]} already exists." );
}
}
$this->nextIndex = max( $this->nextIndex, $row[ $primaryKey ] + 1 );
}
$this->data[] = $row;
$this->saveData();
}
// Get a row by primary key
public function get( $key ) {
$primaryKey = $this->primaryKey;
foreach ( $this->data as $dataRow ) {
if ( $dataRow[ $primaryKey ] === $key ) {
return $dataRow;
}
}
return null;
}
// Update a row by primary key
public function update( $key, $row ) {
$primaryKey = $this->primaryKey;
foreach ( $this->data as &$dataRow ) {
if ( $dataRow[ $primaryKey ] === $key ) {
$dataRow = array_merge( $dataRow, $row );
$this->saveData();
return;
}
}
throw new OutOfBoundsException( "Row with primary key $key does not exist." );
}
// Delete a row by primary key
public function delete( $key ) {
$primaryKey = $this->primaryKey;
foreach ( $this->data as $index => $dataRow ) {
if ( $dataRow[ $primaryKey ] === $key ) {
unset( $this->data[ $index ] );
$this->saveData();
return;
}
}
throw new OutOfBoundsException( "Row with primary key $key does not exist." );
}
// Get all rows with optional sorting
public function getAll( $orderBy = null, $order = 'asc' ) {
$data = $this->data;
if ( $orderBy !== null ) {
usort( $data, function ( $a, $b ) use ( $orderBy, $order ) {
if ( ! isset( $a[ $orderBy ] ) || ! isset( $b[ $orderBy ] ) ) {
return 0;
}
$comparison = $a[ $orderBy ] <=> $b[ $orderBy ];
return $order === 'desc' ? - $comparison : $comparison;
} );
}
return $data;
}
// Get the total number of rows
public function getTotalRows() {
return count( $this->data );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment