PHPackages                             marcocesarato/cpdo - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. marcocesarato/cpdo

ActiveLibrary[Database &amp; ORM](/categories/database)

marcocesarato/cpdo
==================

This package can retrieve PDO query results from cache variables. It extends the base PDO class and override some functions to handle database query execution and store the query results in variables. The class can also return query results for cached queries for previously executed queries to retrieve the results faster for repeated queries.

0.2.3.44(6y ago)43754[1 PRs](https://github.com/marcocesarato/PHP-CPDO/pulls)GPL-3.0-or-laterPHPPHP &gt;=5.1.2

Since Sep 11Pushed 3y agoCompare

[ Source](https://github.com/marcocesarato/PHP-CPDO)[ Packagist](https://packagist.org/packages/marcocesarato/cpdo)[ RSS](/packages/marcocesarato-cpdo/feed)WikiDiscussions master Synced today

READMEChangelog (4)Dependencies (1)Versions (6)Used By (0)

CPDO - Cache PDO Query Class
============================

[](#cpdo---cache-pdo-query-class)

**Version:** 0.2.3.47 beta

**Github:**

**Author:** Marco Cesarato

Description
-----------

[](#description)

This package can retrieve PDO query results from cache variables.

It extends the base PDO class and override some functions to handle database query execution and store the query results in variables.

The class can also return query results for cached queries for previously executed queries to retrieve the results faster for repeated queries.

It permit to have cached `SELECT/SHOW/DESCRIBE` queries on Memory (RAM). Then after the execution the cache will be deleted.

Cache is cleaned on `INSERT/UPDATE/DELETE/TRUNCATE...` only for the single table.

What problem this solves
------------------------

[](#what-problem-this-solves)

When we call the same query (for example on ORM based system) we retrieve from the database the same data doing the same operation and some time we overload the database server (for example retrieving big data multiple times).

This class prevent to do the same query on the database, retrieving the data from memory without overload the database server in some cases.

### Requirements

[](#requirements)

- PHP
- Database

Databases supported (`CPDO::connect`)
-------------------------------------

[](#databases-supported-cpdoconnect)

- 4D
- CUBRID
- Firebird/Interbase
- IBM
- Informix
- MS SQL Server
- MySQL
- ODBC and DB2
- Oracle
- PostgreSQL
- SQLite

Install
-------

[](#install)

### Composer

[](#composer)

1. Install composer
2. Type `composer require marcocesarato/cpdo`
3. Enjoy

Usage
-----

[](#usage)

You have to use this class as PDO.

CPDO introduced these new methods:

### Method `connect`

[](#method-connect)

This feature is a DSN autogeneration and you have to use it instead of the constructor.

#### Usage of `connect`

[](#usage-of-connect)

```
$db = CPDO::connect($database_type, $database_name, $database_host = null, $database_user = null, $database_pswd = null);
```

### Method `getTables`

[](#method-gettables)

Return the names of all database tables as `array`

### Method `backup`

[](#method-backup)

You can backup **Data** (At the moment no TRIGGERS, VIEWS and EVENTS *if you need it you can request it to the developer*). You can choose if you want the tables you want backup through an `array`.

#### Usage of `backup`

[](#usage-of-backup)

```
$db->backup($backup_dir, $backup_tables = '*');
```

Cache
-----

[](#cache)

You can disable/enable the cache using the following methods (default is *disabled*):

```
$db->disableCache();
$db->enableCache();
```

or

```
CPDOCache::disable();
CPDOCache::enable();
```

### Methods available:

[](#methods-available)

- `void CPDOCache::enable()` ENABLE Cache
- `void CPDOCache::disable()` DISABLE Cache
- `void CPDOCache::populate(array $cache)` Populate cache (see below persistent cache)
- `array CPDOCache::retrieve()` Retrieve cache (see below persistent cache)
- `void CPDOCache::addException(string $table_name)` Add not cacheable table
- `void CPDOCache::addExceptions(array $tables_name)` Add not cacheable tables

Debugger
--------

[](#debugger)

You can enable/disable the debugger using the following methods (default is *enabled*):

```
$db->enableDebug();
$db->disableDebug();
```

or

```
CPDOLogger::enable();
CPDOLogger::disable();
```

### Methods available:

[](#methods-available-1)

- `void CPDOLogger::enable()` ENABLE Cache
- `void CPDOLogger::disable()` DISABLE Cache
- `array CPDOLogger::getLogs();` Get complete logs (with time of execution and if cache used)
- `array CPDOLogger::getQueries()` Get all queries requested
- `int CPDOLogger::getCounter()` Get the counter of queries requested
- `void CPDOLogger::cleanLogs();` Clean Logs

### Example of complete logs `getLogs()`

[](#example-of-complete-logs-getlogs)

```
array (
  'count' => 3,
  'queries' =>
  array (
    'SET NAMES \'utf8\'' =>
        array (
          0 =>
          array (
            'time' => 1530610903,
            'execution_time' => 0.000247955322265625,
            'cached' => false,
          ),
          1 =>
            array (
              'time' => 1530610903,
              'execution_time' => 0.000077955322265625,
              'cached' => false,
            ),
        ),
    'SELECT id FROM _deleted_records_ WHERE table = \'settings\' LIMIT 1' =>
        array (
          0 =>
          array (
            'time' => 1530610903,
            'execution_time' => 0.00050687789916992188,
            'cached' => false,
          ),
        ),
  ),
)
```

(Not recommended) Persistent cache
----------------------------------

[](#not-recommended-persistent-cache)

*PS: this usage is not recommended!!!*

If you want a persitent you can use the method `CPDOCache::populate` for populate the cache and `CPDOCache::retrieve` for retrieve the cache.

Thanks these methods you could implement a persistent cache system saving the data encoded (with json or serialization) and after restore the cache.

Pro:

- Less database stress
- Less queries

Cons:

- Could compromise data
- Could be slower (disk performance/clients connected)

### Example of usage

[](#example-of-usage)

```
// Your loader/includes... => with require_once('CPDO.php');

$database_cache_path = '/your/cache/path/database.json';

$cache = file_get_contents($database_cache_path);
$cache = json_decode($cache); // Or unserialize (slower)
CPDOCache::populate($cache);
unset($cache);

// Your code...

$cache = CPDOCache::retrieve();
$cache = json_encode($cache); // Or serialize (slower)
file_put_contents($database_cache_path, $cache);
unset($cache);
```

Methods
-------

[](#methods)

### CPDO

[](#cpdo)

Same methods of PDO in additions the following:

MethodsParametersDescriptionconnectparam $database\_type
 param null $database\_name
 param null $database\_host
 param null $database\_user
 param null $database\_pswd
 param null $database\_charset
 return bool|staticAutogeneration of the DSNenableDebugEnable debugdisableDebugDisable debugenableCacheEnable cachedisableCacheDisable cachegetTablesreturn array|boolGet list of database tablesbackupparam string $tablesBackup database tables or just a tableescapeparam string $valueEscape variable### CPDOLogger

[](#cpdologger)

MethodsParametersDescriptionenableEnable logsdisableDisable logsisEnabledreturn boolReturn if logs are enabledaddLogparam $query
 param $time
 param $cacheAdd new loggetLogsreturn arrayGet LogsgetCounterreturn intGet CountergetQueriesreturn arrayGet CountercleanLogsClean Logs### CPDOCache

[](#cpdocache)

MethodsParametersDescriptiondisableDisable cacheisEnabledreturn boolReturn if cache is enabledpopulateparam $mixed
 return boolPopulate cacheretrievereturn arrayRetrieve CachegetExceptionsreturn arrayGet all excluded tablesaddExceptionparam $excludeAdd exceptionaddExceptionsparam $excludeAdd exceptionssetcacheparam $query
 param $value
 param null $argSet Cachegetcacheparam $query
 param null $arg
 return nullGet Cachedeletecacheparam $queryDelete Cache

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

2432d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f8696e6d4b8a9594f158e63339c5ab818cd416ea6cc1dec9a003c60b984b28ec?d=identicon)[marcocesarato](/maintainers/marcocesarato)

---

Top Contributors

[![marcocesarato](https://avatars.githubusercontent.com/u/36447518?v=4)](https://github.com/marcocesarato "marcocesarato (26 commits)")

---

Tags

cachecachepdocpdodatabasememorypdophp

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/marcocesarato-cpdo/health.svg)

```
[![Health](https://phpackages.com/badges/marcocesarato-cpdo/health.svg)](https://phpackages.com/packages/marcocesarato-cpdo)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M543](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M209](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
