Skip to main content

Models

The Models class provides an active record pattern for database operations, including CRUD functionality with protection against mass assignment vulnerabilities.

Namespace

Sphp\Core\Models

Protected Properties

protected $table;          // Database table name
protected $env;            // Configuration array
protected $db;             // Database instance
protected $fillables = []; // Allowed fields for mass assignment
protected $hidden_fields;  // Fields to hide from output

Methods

create()

Inserts a new record into the database table.
public function create($request)
request
array
required
Associative array of field names and values to insert. Only fields listed in $fillables will be inserted.
result
array
Returns the result from the database query execution

Behavior

  • Filters the request data to only include fields defined in $fillables (protection against mass assignment)
  • Throws an exception if no valid fields are provided
  • Builds a parameterized INSERT query
  • Executes the query using prepared statements

Example

class User extends Models
{
    protected $table = 'users';
    protected $fillables = ['name', 'email', 'password'];
}

$user = new User();
$user->create([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => password_hash('secret', PASSWORD_DEFAULT)
]);

update()

Updates an existing record in the database table.
public function update($request, $id)
request
array
required
Associative array of field names and values to update. Only fields listed in $fillables will be updated.
id
int|string
required
The ID of the record to update
void
void
This method does not return a value

Behavior

  • Filters the request data to only include fields defined in $fillables
  • Throws an exception if no valid fields are provided
  • Builds a parameterized UPDATE query with WHERE id clause
  • Executes the query using prepared statements

Example

$user = new User();
$user->update([
    'name' => 'Jane Doe',
    'email' => '[email protected]'
], 42);

delete()

Deletes a record from the database table by ID.
public function delete($id)
id
int|string
required
The ID of the record to delete
void
void
This method does not return a value

Behavior

  • Throws an exception if no ID is provided
  • Executes a DELETE query with WHERE id clause
  • Uses prepared statements for security

Example

$user = new User();
$user->delete(42);

select()

Performs a SELECT query with flexible filtering, ordering, and limiting options.
public function select(array $columns, array $where = [], string $orderBy = '', int $limit = 0)
columns
array
required
Array of column names to select (e.g., ['id', 'name', 'email'])
where
array
default:"[]"
Associative array of column-value pairs for WHERE conditions. Multiple conditions are combined with AND.
orderBy
string
default:"''"
ORDER BY clause (e.g., 'created_at DESC', 'name ASC')
limit
int
default:"0"
Maximum number of records to return. Use 0 for no limit.
results
array
Returns an array of associative arrays containing the query results

Behavior

  • Throws an exception if columns array is empty
  • Builds a SELECT query with optional WHERE, ORDER BY, and LIMIT clauses
  • All WHERE conditions are combined with AND logic
  • Uses prepared statements to prevent SQL injection

Example

$user = new User();

// Select all columns for active users, ordered by name
$activeUsers = $user->select(
    ['id', 'name', 'email'],
    ['status' => 'active'],
    'name ASC',
    10
);

// Select specific users
$specificUser = $user->select(
    ['*'],
    ['email' => '[email protected]', 'status' => 'active']
);

findByID()

Finds and returns a single record by its ID.
public function findByID($id)
id
int|string
required
The ID of the record to retrieve
record
array
Returns an associative array containing the record data (first result only)

Behavior

  • Throws an exception if no ID is provided
  • Executes a SELECT query with WHERE id clause
  • Returns only the first matching record
  • Note: Does not use prepared statements (consider using select() for safer queries)

Example

$user = new User();
$userData = $user->findByID(42);

echo $userData['name'];  // John Doe
echo $userData['email']; // [email protected]

Usage Pattern

Extend the Models class and define the table and fillable fields:
namespace App\Models;

use Sphp\Core\Models;

class Post extends Models
{
    protected $table = 'posts';
    protected $fillables = ['title', 'content', 'author_id', 'status'];
    protected $hidden_fields = ['deleted_at'];
}

// Create a new post
$post = new Post();
$post->create([
    'title' => 'My First Post',
    'content' => 'This is the content...',
    'author_id' => 1,
    'status' => 'published'
]);

// Find all published posts
$publishedPosts = $post->select(
    ['id', 'title', 'created_at'],
    ['status' => 'published'],
    'created_at DESC',
    20
);

// Update a post
$post->update([
    'title' => 'Updated Title',
    'content' => 'Updated content...'
], 5);

// Delete a post
$post->delete(5);

Mass Assignment Protection

The $fillables array protects against mass assignment vulnerabilities by only allowing specified fields to be inserted or updated:
protected $fillables = ['name', 'email', 'bio'];

// This will only insert name and email (ignoring is_admin)
$user->create([
    'name' => 'John',
    'email' => '[email protected]',
    'is_admin' => true  // This field will be ignored!
]);

Build docs developers (and LLMs) love