Oihana PHP System

PDOModel extends Model uses PDOTrait

A base model class that integrates a PDO instance with dependency injection container support.

This class uses the PDOTrait to provide PDO-related database operations, binding, and fetching.

The model can be initialized with configuration options such as alters, binds, schema, defer assignment, logger, mock objects, and the PDO instance itself.

Tags
throws
ContainerExceptionInterface

If there is a problem retrieving services from the container.

throws
NotFoundExceptionInterface

If a required service is not found in the container.

example
use DI\Container;
use oihana\models\PDOModel;

$container = new Container();

// Configuration array with optional parameters
$config =
[
    'deferAssignment' => true,
    'pdo'             => 'my_pdo_service', // or a PDO instance
    'schema'          => MyEntity::class,
];

// Instantiate the model with the container and configuration
$model = new PDOModel( $container , $config ) ;

// Fetch a single record
$record = $model->fetch('SELECT * FROM users WHERE id = :id', ['id' => 123]);

// Fetch all records
$records = $model->fetchAll('SELECT * FROM users');
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

DEBUG  = 'debug'
The 'debug' parameter constant.
MOCK  = 'mock'
The 'mock' parameter constant.

Properties

$container  : Container
The DI container reference.
$debug  : bool
Indicates if use the debug mode.
$deferAssignment  : bool|null
Indicates if the the constructor is called before setting properties.
$mock  : bool
The mock flag to test the model.
$pdo  : PDO|null
The PDO reference.

Methods

__construct()  : mixed
Creates a new PDOModel instance.
__toString()  : string
Returns a String representation of the object.
bindValues()  : void
Bind named parameters to a prepared PDO statement.
fetch()  : mixed
fetchAll()  : array<string|int, mixed>
fetchAllAsGenerator()  : Generator<string|int, object>
Execute a SELECT query and fetch all results as a generator.
fetchColumn()  : mixed
fetchColumnArray()  : array<int, string>
Fetch a list of single-column results.
initializeDebug()  : static
Initialize the debug flag.
initializeDefaultFetchMode()  : void
Set the default fetch mode on the statement.
initializeDeferAssignment()  : static
Initialize the 'deferAssignment' property.
initializeMock()  : static
Initialize the mock flag.
initializePDO()  : static
Initialize the PDO instance from a config array or dependency injection container.
isConnected()  : bool
Indicates if the PDO is connected.
isDebug()  : bool
Check if debug mode is active.
isMock()  : bool
Check if mock mode is active.

Constants

DEBUG

The 'debug' parameter constant.

public mixed DEBUG = 'debug'

MOCK

The 'mock' parameter constant.

public mixed MOCK = 'mock'

Properties

$container

The DI container reference.

public Container $container

The dependency injection container instance.

$debug

Indicates if use the debug mode.

public bool $debug = false

$deferAssignment

Indicates if the the constructor is called before setting properties.

public bool|null $deferAssignment = false

Only if the schema property is defined.

$mock

The mock flag to test the model.

public bool $mock = false

$pdo

The PDO reference.

public PDO|null $pdo = null

Methods

__construct()

Creates a new PDOModel instance.

public __construct(Container $container[, PDO|string|null} $init = [] ]) : mixed

Sets internal properties from the provided configuration array and initializes logger, mock, and PDO.

Parameters
$container : Container

The DI container to retrieve services like PDO and logger.

$init : PDO|string|null} = []

Optional initialization array with keys:

  • ModelParam::ALTERS : array of alterations to apply
  • ModelParam::BINDS : array of binds for queries
  • ModelParam::DEFER_ASSIGNMENT : bool whether to defer property assignment on fetch
  • ModelParam::SCHEMA : string class name of schema for fetch mode
  • ModelParam::PDO : PDO instance or service name in container
Tags
throws
ContainerExceptionInterface

If container service retrieval fails.

throws
NotFoundExceptionInterface

If container service not found.

__toString()

Returns a String representation of the object.

public __toString() : string
Tags
throws
ReflectionException
Return values
string

A string representation of the object.

bindValues()

Bind named parameters to a prepared PDO statement.

public bindValues(PDOStatement $statement[, array<string|int, mixed> $bindVars = [] ]) : void
Parameters
$statement : PDOStatement

The PDO statement.

$bindVars : array<string|int, mixed> = []

Associative array of bindings. Supports:

  • ['id' => 5]
  • ['id' => [5, PDO::PARAM_INT]]

fetch()

public fetch(string $query[, array<string|int, mixed> $bindVars = = '[]' ]) : mixed

Fetch a single record from the database.

Parameters
$query : string
$bindVars : array<string|int, mixed> = = '[]'

fetchAll()

public fetchAll(string $query[, array<string|int, mixed> $bindVars = = '[]' ]) : array<string|int, mixed>

Fetch all matching records from the database.

Parameters
$query : string
$bindVars : array<string|int, mixed> = = '[]'
Return values
array<string|int, mixed>

fetchAllAsGenerator()

Execute a SELECT query and fetch all results as a generator.

public fetchAllAsGenerator(string $query[, array<string|int, mixed> $bindVars = [] ][, bool $throwable = false ]) : Generator<string|int, object>

Results are yielded one by one as objects or schema instances. Alteration is applied via AlterDocumentTrait.

Parameters
$query : string

The SQL query to execute.

$bindVars : array<string|int, mixed> = []

Optional bindings for the query.

$throwable : bool = false

Whether to rethrow exceptions instead of handling them internally (default: false).

Tags
throws
ContainerExceptionInterface
throws
DependencyException
throws
NotFoundException
throws
NotFoundExceptionInterface
throws
ReflectionException
Return values
Generator<string|int, object>

A generator yielding results one by one.

fetchColumn()

public fetchColumn(string $query[, array<string|int, mixed> $bindVars = = '[]' ][, int $column = = '0' ]) : mixed

Fetch a single column from the first row.

Parameters
$query : string
$bindVars : array<string|int, mixed> = = '[]'
$column : int = = '0'

fetchColumnArray()

Fetch a list of single-column results.

public fetchColumnArray(string $query[, array<string|int, mixed> $bindVars = [] ][, bool $throwable = false ]) : array<int, string>
Parameters
$query : string

The SQL query to execute.

$bindVars : array<string|int, mixed> = []

Optional bindings for the query.

$throwable : bool = false

Whether to rethrow exceptions instead of handling them internally (default: false).

Tags
throws
Exception
Return values
array<int, string>

initializeDebug()

Initialize the debug flag.

public initializeDebug([array<string|int, mixed> $init = [] ][, bool $defaultValue = false ]) : static

This method sets the $debug property using the value provided in the $init array, or falls back to the current $debug value. If the value in $init is not a boolean, the provided $defaultValue is used instead.

Parameters
$init : array<string|int, mixed> = []

Optional initialization array.

$defaultValue : bool = false

Default value to use if the init value is not a boolean.

Return values
static

Returns the current instance for chaining.

initializeDefaultFetchMode()

Set the default fetch mode on the statement.

public initializeDefaultFetchMode(PDOStatement $statement) : void

Uses FETCH_ASSOC by default or FETCH_CLASS (with optional FETCH_PROPS_LATE) if a schema class is defined and exists.

Parameters
$statement : PDOStatement

The PDO statement to configure.

initializeDeferAssignment()

Initialize the 'deferAssignment' property.

public initializeDeferAssignment([array<string|int, mixed> $init = [] ]) : static
Parameters
$init : array<string|int, mixed> = []
Return values
static

initializeMock()

Initialize the mock flag.

public initializeMock([array<string|int, mixed> $init = [] ][, bool $defaultValue = false ]) : static

This method sets the $mock property using the value provided in the $init array, or falls back to the current $mock value. If the value in $init is not a boolean, the provided $defaultValue is used instead.

Parameters
$init : array<string|int, mixed> = []

Optional initialization array.

$defaultValue : bool = false

Default value to use if the init value is not a boolean.

Return values
static

Returns the current instance for chaining.

initializePDO()

Initialize the PDO instance from a config array or dependency injection container.

public initializePDO([array<string|int, mixed> $init = [] ][, Container|null $container = null ]) : static
Parameters
$init : array<string|int, mixed> = []

Configuration array. Expects ModelParam::PDO ('pdo') as key.

$container : Container|null = null

Optional DI container to resolve the PDO service.

Tags
throws
ContainerExceptionInterface
throws
NotFoundExceptionInterface
Return values
static

isConnected()

Indicates if the PDO is connected.

public isConnected() : bool
Return values
bool

isDebug()

Check if debug mode is active.

public isDebug([array<string|int, mixed> $init = [] ]) : bool

This method returns the boolean value of the debug flag. If a value is provided in the $init array, it is used; otherwise the current $debug property is used. Non-boolean values in $init are treated as false.

Parameters
$init : array<string|int, mixed> = []

Optional array containing a debug value.

Return values
bool

True if debug mode is active, false otherwise.

isMock()

Check if mock mode is active.

public isMock([array<string|int, mixed> $init = [] ]) : bool

Mock mode is only active if debug mode is active as well. If a value is provided in the $init array, it is used; otherwise the current $mock property is used. Non-boolean values in $init are treated as false.

Parameters
$init : array<string|int, mixed> = []

Optional array containing a mock value.

Return values
bool

True if mock mode is active, false otherwise.


        
On this page

Search results