Skip to content

XoopsObject Class

The XoopsObject class is the fundamental base class for all data objects in the XOOPS system. It provides a standardized interface for managing object properties, validation, dirty tracking, and serialization.

namespace Xoops\Core;
class XoopsObject
{
protected array $vars = [];
protected array $cleanVars = [];
protected bool $isNew = true;
protected array $errors = [];
}
XoopsObject
├── XoopsUser
├── XoopsGroup
├── XoopsModule
├── XoopsBlock
├── XoopsComment
├── XoopsNotification
├── XoopsConfig
└── [Custom Module Objects]
PropertyTypeVisibilityDescription
$varsarrayprotectedStores variable definitions and values
$cleanVarsarrayprotectedStores sanitized values for database operations
$isNewboolprotectedIndicates if object is new (not yet in database)
$errorsarrayprotectedStores validation and error messages
public function __construct()

Creates a new XoopsObject instance. The object is marked as new by default.

Example:

$object = new XoopsObject();
// Object is new and has no defined variables

Initializes a variable definition for the object.

public function initVar(
string $key,
int $dataType,
mixed $value = null,
bool $required = false,
int $maxlength = null,
string $options = ''
): void

Parameters:

ParameterTypeDescription
$keystringVariable name
$dataTypeintData type constant (see Data Types)
$valuemixedDefault value
$requiredboolWhether field is required
$maxlengthintMaximum length for string types
$optionsstringAdditional options

Data Types:

ConstantValueDescription
XOBJ_DTYPE_TXTBOX1Text box input
XOBJ_DTYPE_TXTAREA2Textarea content
XOBJ_DTYPE_INT3Integer value
XOBJ_DTYPE_URL4URL string
XOBJ_DTYPE_EMAIL5Email address
XOBJ_DTYPE_ARRAY6Serialized array
XOBJ_DTYPE_OTHER7Custom type
XOBJ_DTYPE_SOURCE8Source code
XOBJ_DTYPE_STIME9Short time format
XOBJ_DTYPE_MTIME10Medium time format
XOBJ_DTYPE_LTIME11Long time format
XOBJ_DTYPE_FLOAT12Floating point
XOBJ_DTYPE_DECIMAL13Decimal number
XOBJ_DTYPE_ENUM14Enumeration

Example:

class MyObject extends XoopsObject
{
public function __construct()
{
parent::__construct();
$this->initVar('id', XOBJ_DTYPE_INT, null, false);
$this->initVar('title', XOBJ_DTYPE_TXTBOX, '', true, 255);
$this->initVar('content', XOBJ_DTYPE_TXTAREA, '', false);
$this->initVar('email', XOBJ_DTYPE_EMAIL, '', true, 100);
$this->initVar('created', XOBJ_DTYPE_INT, time(), false);
$this->initVar('status', XOBJ_DTYPE_INT, 1, true);
}
}

Sets the value of a variable.

public function setVar(
string $key,
mixed $value,
bool $notGpc = false
): bool

Parameters:

ParameterTypeDescription
$keystringVariable name
$valuemixedValue to set
$notGpcboolIf true, value is not from GET/POST/COOKIE

Returns: bool - True if successful, false otherwise

Example:

$object = new MyObject();
$object->setVar('title', 'Hello World');
$object->setVar('content', '<p>Content here</p>', true); // Not from user input
$object->setVar('status', 1);

Retrieves the value of a variable with optional formatting.

public function getVar(
string $key,
string $format = 's'
): mixed

Parameters:

ParameterTypeDescription
$keystringVariable name
$formatstringOutput format

Format Options:

FormatDescription
's'Show - HTML entities escaped for display
'e'Edit - For form input values
'p'Preview - Similar to show
'f'Form data - Raw for form processing
'n'None - Raw value, no formatting

Returns: mixed - The formatted value

Example:

$object = new MyObject();
$object->setVar('title', 'Hello <World>');
echo $object->getVar('title', 's'); // "Hello &lt;World&gt;"
echo $object->getVar('title', 'e'); // "Hello &lt;World&gt;" (for input value)
echo $object->getVar('title', 'n'); // "Hello <World>" (raw)
// For array data types
$object->setVar('options', ['a', 'b', 'c']);
$options = $object->getVar('options', 'n'); // Returns array

Sets multiple variables at once from an array.

public function setVars(
array $values,
bool $notGpc = false
): void

Parameters:

ParameterTypeDescription
$valuesarrayAssociative array of key => value pairs
$notGpcboolIf true, values are not from GET/POST/COOKIE

Example:

$object = new MyObject();
$object->setVars([
'title' => 'My Title',
'content' => 'My content',
'status' => 1
]);
// From database (not user input)
$object->setVars($row, true);

Retrieves all variable values.

public function getValues(
array $keys = null,
string $format = 's',
int $maxDepth = 1
): array

Parameters:

ParameterTypeDescription
$keysarraySpecific keys to retrieve (null for all)
$formatstringOutput format
$maxDepthintMaximum depth for nested objects

Returns: array - Associative array of values

Example:

$object = new MyObject();
// Get all values
$allValues = $object->getValues();
// Get specific values
$subset = $object->getValues(['title', 'status']);
// Get raw values for database
$rawValues = $object->getValues(null, 'n');

Assigns a value directly without validation (use with caution).

public function assignVar(
string $key,
mixed $value
): void

Parameters:

ParameterTypeDescription
$keystringVariable name
$valuemixedValue to assign

Example:

// Direct assignment from trusted source (e.g., database)
$object->assignVar('id', $row['id']);
$object->assignVar('created', $row['created']);

Sanitizes all variables for database operations.

public function cleanVars(): bool

Returns: bool - True if all variables are valid

Example:

$object = new MyObject();
$object->setVar('title', 'Test');
$object->setVar('email', 'user@example.com');
if ($object->cleanVars()) {
// Variables are sanitized and ready for database
$cleanData = $object->cleanVars;
} else {
// Validation errors occurred
$errors = $object->getErrors();
}

Checks or sets whether the object is new.

public function isNew(): bool
public function setNew(): void
public function unsetNew(): void

Example:

$object = new MyObject();
echo $object->isNew(); // true
$object->unsetNew();
echo $object->isNew(); // false
$object->setNew();
echo $object->isNew(); // true

Adds an error message.

public function setErrors(string|array $error): void

Example:

$object->setErrors('Title is required');
$object->setErrors(['Field 1 error', 'Field 2 error']);

Retrieves all error messages.

public function getErrors(): array

Example:

$errors = $object->getErrors();
foreach ($errors as $error) {
echo $error . "\n";
}

Returns errors formatted as HTML.

public function getHtmlErrors(): string

Example:

if (!$object->cleanVars()) {
echo '<div class="error">' . $object->getHtmlErrors() . '</div>';
}

Converts the object to an array.

public function toArray(): array

Example:

$object = new MyObject();
$object->setVar('title', 'Test');
$data = $object->toArray();
// ['title' => 'Test', ...]

Returns the variable definitions.

public function getVars(): array

Example:

$vars = $object->getVars();
foreach ($vars as $key => $definition) {
echo "Field: $key, Type: {$definition['data_type']}\n";
}

<?php
/**
* Custom Article Object
*/
class Article extends XoopsObject
{
/**
* Constructor - Initialize all variables
*/
public function __construct()
{
parent::__construct();
// Primary key
$this->initVar('article_id', XOBJ_DTYPE_INT, null, false);
// Required fields
$this->initVar('title', XOBJ_DTYPE_TXTBOX, '', true, 255);
$this->initVar('author_id', XOBJ_DTYPE_INT, 0, true);
// Optional fields
$this->initVar('summary', XOBJ_DTYPE_TXTAREA, '', false);
$this->initVar('content', XOBJ_DTYPE_TXTAREA, '', false);
$this->initVar('category_id', XOBJ_DTYPE_INT, 0, false);
// Timestamps
$this->initVar('created', XOBJ_DTYPE_INT, time(), false);
$this->initVar('updated', XOBJ_DTYPE_INT, time(), false);
// Status flags
$this->initVar('published', XOBJ_DTYPE_INT, 0, false);
$this->initVar('views', XOBJ_DTYPE_INT, 0, false);
// Metadata as array
$this->initVar('meta', XOBJ_DTYPE_ARRAY, [], false);
}
/**
* Get formatted creation date
*/
public function getCreatedDate(string $format = 'Y-m-d H:i:s'): string
{
return date($format, $this->getVar('created', 'n'));
}
/**
* Check if article is published
*/
public function isPublished(): bool
{
return $this->getVar('published', 'n') == 1;
}
/**
* Increment view counter
*/
public function incrementViews(): void
{
$views = $this->getVar('views', 'n');
$this->setVar('views', $views + 1);
}
/**
* Custom validation
*/
public function validate(): bool
{
$this->errors = [];
// Title validation
$title = trim($this->getVar('title', 'n'));
if (empty($title)) {
$this->setErrors('Title is required');
} elseif (strlen($title) < 5) {
$this->setErrors('Title must be at least 5 characters');
}
// Author validation
if ($this->getVar('author_id', 'n') <= 0) {
$this->setErrors('Author is required');
}
return empty($this->errors);
}
}
// Usage
$article = new Article();
$article->setVar('title', 'My First Article');
$article->setVar('author_id', 1);
$article->setVar('content', '<p>Article content here...</p>', true);
$article->setVar('meta', [
'keywords' => ['xoops', 'cms', 'php'],
'description' => 'An example article'
]);
if ($article->validate() && $article->cleanVars()) {
// Save to database via handler
$handler = xoops_getModuleHandler('article', 'mymodule');
$handler->insert($article);
echo "Article saved with ID: " . $article->getVar('article_id');
} else {
echo "Errors: " . $article->getHtmlErrors();
}
  1. Always Initialize Variables: Define all variables in the constructor using initVar()

  2. Use Appropriate Data Types: Choose the correct XOBJ_DTYPE_* constant for validation

  3. Handle User Input Carefully: Use setVar() with $notGpc = false for user input

  4. Validate Before Saving: Always call cleanVars() before database operations

  5. Use Format Parameters: Use the appropriate format in getVar() for the context

  6. Extend for Custom Logic: Add domain-specific methods in subclasses

  • XoopsObjectHandler - Handler pattern for object persistence
  • ../Database/Criteria - Query building with Criteria
  • ../Database/XoopsDatabase - Database operations

See also: XOOPS Source Code