├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── MPLT.php ├── README.md ├── bin └── .gitignore ├── checksums ├── composer.json ├── composer.lock ├── docs ├── DI.rst ├── Download.rst ├── Install.rst ├── Quickstart.rst ├── _templates │ └── page.html ├── about.rst ├── cache.rst ├── cache │ ├── APC.rst │ ├── CacheInterface.rst │ ├── disk.rst │ ├── memcache.rst │ └── redis.rst ├── conf.py ├── database.rst ├── database │ ├── AutoExecute.rst │ ├── Cache.rst │ ├── CacheFlush.rst │ ├── Close.rst │ ├── CompleteTrans.rst │ ├── ErrorMsg.rst │ ├── ErrorNum.rst │ ├── Execute.rst │ ├── FetchMode.rst │ ├── Insert_Id.rst │ ├── PClose.rst │ ├── PExecute.rst │ ├── PQuery.rst │ ├── Prepare.rst │ ├── RollBackTrans.rst │ ├── StartTrans.rst │ ├── UUID.rst │ ├── X.rst │ ├── construct.rst │ ├── csv.rst │ ├── debug.rst │ ├── fill.py │ ├── forceTruncate.rst │ ├── getASSOC.rst │ ├── getAll.rst │ ├── getClientVersion.rst │ ├── getCol.rst │ ├── getColumnNames.rst │ ├── getNumOfFields.rst │ ├── getNumOfRows.rst │ ├── getNumOfRowsAffected.rst │ ├── getOne.rst │ ├── getRow.rst │ ├── getServerVersion.rst │ ├── isConnected.rst │ ├── map.rst │ ├── multipleInsert.rst │ ├── qstr.rst │ ├── query.rst │ ├── renumber.rst │ └── useCache.rst ├── examples.rst ├── examples │ └── basic.rst ├── index.rst ├── issues.rst ├── navicat.jpg ├── navicat.rst ├── prepared_statements.rst ├── queue.rst ├── queue │ ├── QueueInterface.rst │ └── SQLite.rst ├── sessions.rst ├── sessions │ ├── Example.rst │ ├── Files.rst │ ├── Memcache.rst │ ├── MySQL.rst │ ├── Redis.rst │ ├── SQLite.rst │ ├── construct.rst │ ├── delSessionRef.rst │ ├── getSessionRef.rst │ ├── getSessionsRefs.rst │ └── regenerate_id.rst └── tests.rst ├── examples ├── README.markdown ├── all_together │ ├── database-cache-sessions.php │ └── di.php ├── cache │ ├── cache-group-DSN.php │ ├── cache-group.php │ ├── cache.php │ ├── cache_disk.php │ ├── cache_memcache.php │ ├── cache_redis.php │ └── cache_redis2.php ├── database │ ├── 2databases.php │ ├── X.php │ ├── cleanDB.php │ ├── cluster.php │ ├── csv.php │ ├── iterator.php │ ├── locale.php │ ├── map.php │ ├── multipleinsert.php │ ├── preparedStatements.php │ ├── query_Execute.php │ ├── queue.php │ ├── redis.php │ ├── select_db.php │ ├── start.php │ ├── transaction_concurrent_process.php │ └── transactions.php ├── queue │ └── queue.php ├── sessions │ ├── REF.php │ ├── curl.php │ ├── sessions-redis.php │ ├── sessions.php │ ├── sessions_1.php │ ├── sqlite-encryption.php │ └── sqliteSessions.php └── world.sql.gz ├── phpunit.xml.dist ├── src ├── DALMP │ ├── Cache.php │ ├── Cache │ │ ├── APC.php │ │ ├── CacheInterface.php │ │ ├── Disk.php │ │ ├── Memcache.php │ │ └── Redis.php │ ├── DI.php │ ├── Database.php │ ├── Loader.php │ ├── Logger.php │ ├── Queue.php │ ├── Queue │ │ ├── Gearman.php │ │ ├── QueueInterface.php │ │ └── SQLite.php │ ├── Sessions.php │ ├── Sessions │ │ ├── Files.php │ │ ├── Memcache.php │ │ ├── MySQL.php │ │ ├── Redis.php │ │ └── SQLite.php │ └── abstractDI.php └── dalmp.php └── tests ├── test_cache_base.php ├── test_cache_disk.php ├── test_cache_memcache.php ├── test_cache_redis.php ├── test_dalmp.php ├── test_dalmp_cache_base.php ├── test_dalmp_cache_disk.php ├── test_dalmp_cache_memcache.php ├── test_dalmp_cache_redis.php ├── test_sessions_base.php ├── test_sessions_memcache.php ├── test_sessions_mysql.php └── test_sessions_redis.php /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.db 3 | vendor 4 | phpunit.xml 5 | build 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | php: 3 | - 5.5 4 | - 5.4 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) Nicolas de Bari Embriz Garcia Rojas 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of DALMP nor the names of its contributors may be 13 | used to endorse or promote products derived from this software without 14 | specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY 17 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MPLT.php: -------------------------------------------------------------------------------- 1 | 7 | * @license BSD License 8 | */ 9 | class MPLT 10 | { 11 | private $decimals; 12 | private $time_start; 13 | private $time_end; 14 | private $marks = array(); 15 | 16 | /** 17 | * constructor 18 | * 19 | * @param int $decimals 20 | */ 21 | public function __construct($decimals = 4) 22 | { 23 | $this->time_start = microtime(true); 24 | $this->decimals = $decimals; 25 | } 26 | 27 | /** 28 | * stop 29 | */ 30 | public function Stop() 31 | { 32 | $this->time_end = microtime(true); 33 | } 34 | 35 | /** 36 | * setMark 37 | * 38 | * @param string $name 39 | */ 40 | public function setMark($name = null) 41 | { 42 | $mark = microtime(true) - $this->time_start; 43 | $last_mark = end($this->marks)[0]; 44 | $diff = $mark - $last_mark; 45 | $mark = number_format($mark, $this->decimals); 46 | $diff = number_format($diff, $this->decimals); 47 | if ($name && $name != 'total') { 48 | $this->marks[$name] = array($mark, $diff); 49 | } else { 50 | $this->marks[] = array($mark, $diff); 51 | } 52 | } 53 | 54 | /** 55 | * getMark 56 | * 57 | * @param string $name 58 | * @return array 59 | */ 60 | public function getMark($name = null) 61 | { 62 | return $name ? $this->marks[$name] : reset($this->marks); 63 | } 64 | 65 | /** 66 | * getMarks 67 | * 68 | * @return array 69 | */ 70 | public function getMarks() 71 | { 72 | return $this->marks; 73 | } 74 | 75 | /** 76 | * printMarks 77 | */ 78 | public function printMarks() 79 | { 80 | if ($this->marks) { 81 | $pad = $this->decimals * 2; 82 | $max_length = max(array_map('strlen', array_keys($this->marks))); 83 | 84 | if ($pad < $max_length) { 85 | $pad = $max_length + 2; 86 | } 87 | 88 | echo str_pad('mark', $pad), str_pad('time', $pad), 'elapsed-time', $this->isCli(1); 89 | foreach ($this->marks as $mark => $values) { 90 | echo str_pad($mark, $pad), str_pad($values[0], $pad), $values[1], $this->isCli(1); 91 | } 92 | } else { 93 | echo 'no defined marks', $this->isCli(1); 94 | } 95 | } 96 | 97 | /** 98 | * getPageLoadTime 99 | * 100 | * @param bool $marks 101 | */ 102 | public function getPageLoadTime($marks = false) 103 | { 104 | if (empty($this->time_end)) { 105 | $this->Stop(); 106 | } 107 | 108 | $lt = number_format($this->time_end - $this->time_start, $this->decimals); 109 | 110 | if ($marks) { 111 | $this->marks['total'] = $lt; 112 | 113 | return $this->marks; 114 | } else { 115 | return $lt; 116 | } 117 | } 118 | 119 | /** 120 | * getMemoryUsage 121 | * 122 | * @param bool $convert "Human-readable" output. 123 | */ 124 | public function getMemoryUsage($convert = false) 125 | { 126 | return $convert ? $this->convert(memory_get_usage(true)) : memory_get_usage(true); 127 | } 128 | 129 | /** 130 | * convert 131 | * 132 | * @param int $size 133 | */ 134 | public function convert($size) 135 | { 136 | $unit = array('B','KB','MB','GB','TB','PB'); 137 | 138 | return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; 139 | } 140 | 141 | /** 142 | * isCli() 143 | * 144 | * @param boolean $eol 145 | * @return boolean or PHP_EOL,
146 | */ 147 | public function isCli($eol = null) 148 | { 149 | ($cli = (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']))) && $cli = $eol ? PHP_EOL : true; 150 | 151 | return $cli ?: ($eol ? '
' : false); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DALMP 2 | ===== 3 | 4 | **Database Abstraction Layer for MySQL using PHP** 5 | 6 | 0% fat and extremely easy to use. Only connect to database when needed. 7 | 8 | Examples and documentation at: http://docs.dalmp.com 9 | 10 | 11 | Clone the repository: 12 | 13 | 14 | $ git clone https://github.com/nbari/DALMP.git dalmp 15 | 16 | 17 | To Install visit http://docs.dalmp.com/en/latest/Install.html 18 | 19 | Thanks 20 | ------ 21 | 22 | Many thanks [Navicat](http://www.navicat.com) for supporting Open Source projects. 23 | 24 | ![navicat](https://raw.githubusercontent.com/nbari/DALMP/master/docs/navicat.jpg) 25 | 26 | Details 27 | ------- 28 | 29 | * [Dependecy Injector](http://docs.dalmp.com/en/latest/DI.html) (DI) support, load once, trigger when required. 30 | * [APC](http://docs.dalmp.com/en/latest/cache/APC.html), [Disk](http://docs.dalmp.com/en/latest/cache/disk.html), [Memcache](http://docs.dalmp.com/en/latest/cache/memcache.html), [Redis.io](http://docs.dalmp.com/en/latest/cache/redis.html>) cache support. 31 | * Group [caching cache](http://docs.dalmp.com/en/latest/cache.html) by groups and flush by groups or individual keys. 32 | * [Prepared statements](http://docs.dalmp.com/en/latest/prepared_statements.html) ready, support dynamic building queries, auto detect types (i,d,s,b). 33 | * Secure connections with [SSL](http://docs.dalmp.com/en/latest/Quickstart.html#ssl). 34 | * [SQLite3 Encryption](http://docs.dalmp.com/en/latest/queue/SQLite.html). 35 | * Save [sessions in database](http://docs.dalmp.com/en/latest/sessions.html) (mysql/sqlite) or a cache like redis/memcache/apc. 36 | * Easy to use/install/adapt. 37 | * Nested [Transactions](http://docs.dalmp.com/en/latest/database/StartTrans.html) (SAVEPOINT / ROLLBACK TO SAVEPOINT). 38 | * Support connections via [unix_sockets](http://docs.dalmp.com/en/latest/Quickstart.html#example-using-a-socket). 39 | * SQL [queues](http://docs.dalmp.com/en/latest/queue.html). 40 | * Export to [CSV](http://docs.dalmp.com/en/latest/database/csv.html). 41 | * Trace/measure everything enabling the [debugger](http://docs.dalmp.com/en/latest/database/debug.htm). 42 | * Works out of the box with Cloud databases like [Amazon RDS](http://aws.amazon.com/rds/) or [Google cloud](https://developers.google.com/cloud-sql/). 43 | * Lazy database connection. Connect only when needed. 44 | * [PSR-0](http://www.php-fig.org/psr/psr-0/) compliance. 45 | 46 | 47 | Requirements 48 | ------------ 49 | 50 | * [PHP](http://www.php.net>) >= 5.4 51 | * A [MySQL](http://www.mysql.org) server to connect via host or [unix sockets](http://en.wikipedia.org/wiki/Unix_domain_socket). 52 | 53 | To use the cache features you need either the redis, memcache or APC extensions 54 | compiled, otherwise disk cache will be used. 55 | 56 | * Redis extension - http://github.com/nicolasff/phpredis 57 | * Memcache PECL extencsion - http://pecl.php.net/package/memcache 58 | * APC PECL extension - http://pecl.php.net/package/APC 59 | 60 | If you want to store session encrypted then you need SQLite3 Encryption http://sqlcipher.net. 61 | 62 | **DALMP** does not use [PDO](http://www.php.net/pdo), so do not worry if your PHP does not have the pdo 63 | extension. 64 | 65 | On [FreeBSD](http://www.freebsd.org) you can install **DALMP** from ports: /usr/ports/databases/dalmp 66 | -------------------------------------------------------------------------------- /bin/.gitignore: -------------------------------------------------------------------------------- 1 | composer.phar 2 | phpunit 3 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "authors": [ 3 | { 4 | "email": "nbari@dalmp.com", 5 | "name": "Nicolas Embriz" 6 | } 7 | ], 8 | "autoload": { 9 | "psr-0": { 10 | "DALMP\\": "src/" 11 | } 12 | }, 13 | "config": { 14 | "bin-dir": "bin" 15 | }, 16 | "description": "Database Abstraction Layer for MySQL using PHP", 17 | "homepage": "http://www.dalmp.com", 18 | "keywords": [ 19 | "database", 20 | "cache", 21 | "sessions" 22 | ], 23 | "license": "BSD-3-Clause", 24 | "name": "dalmp/dalmp", 25 | "require": { 26 | "ext-mysqli": "*", 27 | "php": ">=5.4.0" 28 | }, 29 | "require-dev": { 30 | "phpunit/php-invoker": "*", 31 | "phpunit/phpunit": "4.1.*" 32 | }, 33 | "suggest": { 34 | "ext-hash": "hash_algos", 35 | "ext-memcache": "Use memcache as cache engine", 36 | "ext-redis": "Use redis as cache engine", 37 | "ext-session": "handle sessions", 38 | "ext-sqlite3": "Use sqlite for queues" 39 | }, 40 | "type": "library" 41 | } 42 | -------------------------------------------------------------------------------- /docs/DI.rst: -------------------------------------------------------------------------------- 1 | Dependency injection 2 | ==================== 3 | 4 | **DALMP** offers a set of classes that allows you to work with 5 | `MySQL `_, 6 | `Cache `_ backends and 7 | `sessions `_, 8 | but when trying to use all this together, some 9 | perfomance issues may be raised, so to deal with this, a DI 10 | (`dependecy injector `_) is high recomendable. 11 | 12 | The idea of using a DI is to load once, and use any time with out need to 13 | reload the objects. 14 | 15 | 16 | abstractDI 17 | .......... 18 | 19 | `abstractDI `_ is the name of an `abstrac class `_ that works as a base for building a dependecy injector. 20 | 21 | 22 | .. note:: 23 | 24 | The abstracDI class can be used as a base for any project not only **DALMP** 25 | 26 | DI 27 | .. 28 | 29 | `DI (Dependecy Injector) `_ 30 | extends ``abstractDI`` and creates the DI for **DALMP**. 31 | 32 | 33 | Example 34 | ....... 35 | 36 | Using mysql, cache (redis), sessions. 37 | 38 | .. code-block:: php 39 | :linenos: 40 | :emphasize-lines: 5 41 | 42 | database($DSN); 56 | 57 | $cache = $di->cache($redis_cache); 58 | 59 | $sessions = $di->sessions($di->sessions_redis($redis_cache), 'sha512'); 60 | $sessions->regenerate_id(true); 61 | 62 | $db->useCache($cache); 63 | 64 | $now = $db->CachegetOne('SELECT NOW()'); 65 | 66 | echo $now, PHP_EOL; 67 | 68 | echo session_id(); 69 | 70 | 71 | TODO Examples 72 | -------------------------------------------------------------------------------- /docs/Download.rst: -------------------------------------------------------------------------------- 1 | Download 2 | ======== 3 | 4 | Zip File: `https://github.com/nbari/dalmp/zipball/master 5 | `_ 6 | 7 | Tar Ball: `https://github.com/nbari/dalmp/tarball/master 8 | `_ 9 | 10 | View on GitHub: `https://github.com/nbari/dalmp 11 | `_ 12 | 13 | Clone the repository: 14 | 15 | .. code-block:: sh 16 | 17 | $ git clone git://github.com/nbari/DALMP.git dalmp 18 | -------------------------------------------------------------------------------- /docs/Install.rst: -------------------------------------------------------------------------------- 1 | Install 2 | ======= 3 | 4 | 5 | Clone the repository: 6 | 7 | .. code-block:: sh 8 | 9 | $ git clone git://github.com/nbari/DALMP.git dalmp 10 | 11 | 12 | Composer 13 | ........ 14 | 15 | 16 | A basic `composer.json `_ file: 17 | 18 | .. code-block:: json 19 | :linenos: 20 | 21 | { 22 | "require": { 23 | "DALMP/dalmp": "*" 24 | }, 25 | "minimum-stability": "dev" 26 | } 27 | 28 | .. code-block:: sh 29 | 30 | $ composer.phar install 31 | 32 | .. seealso:: 33 | 34 | `composer `_ 35 | -------------------------------------------------------------------------------- /docs/_templates/page.html: -------------------------------------------------------------------------------- 1 | {% extends "!page.html" %} 2 | 3 | {% block extrahead %} 4 | 5 | 10 | {% endblock %} 11 | 12 | {# To customize for your project, search and replace 'labibi' stuff. 13 | You might also want to replace the UA- string for google analytics. 14 | 15 | Set what you need in conf.py 16 | #} 17 | 18 | {# set in conf.py: google_analytics_id = 'UA-36028965-1' #} 19 | {# set in conf.py: disqus_shortname = 'labibi' #} 20 | 21 | {# set these in conf.py: 22 | github_base_account = 'ctb' 23 | github_project = 'labibi' 24 | #} 25 | 26 | {%- block body %} 27 | {{ super() }} 28 | 29 |

30 | Thanks Navicat for supporting Open Source projects. 31 |

32 | 33 |

34 | Navicat 35 |

36 | 37 |
38 |
39 | 40 |

41 | A great amount of time has been spent creating, crafting and maintaining this software, please consider donating. 42 |

43 | 44 |

Donating helps ensure continued support, development and availability.

45 |

46 | dalmp 47 |

48 |
49 |
50 | 61 | 62 | comments powered by Disqus 63 | 64 | 65 | 70 | 71 | {%- endblock %} 72 | -------------------------------------------------------------------------------- /docs/about.rst: -------------------------------------------------------------------------------- 1 | DALMP 2 | ===== 3 | 4 | **Database Abstraction Layer for MySQL using PHP** 5 | 6 | 7 | What & Why DALMP 8 | ................ 9 | 10 | `PHP `_ and `MySQL `_ is one of the most popular combinations used in web applications, 11 | sometimes this "combo" join forces with tools like: redis, memcache, APC, etc, 12 | always trying to achieve the best possible performance. 13 | 14 | Setting all this together becomes tricky, especially when your goals are "speed 15 | & security" and you have a short deadline. 16 | 17 | DALMP makes all this integration without hassle, offering several methods that 18 | can help the developer to focus more in optimizing his 'SQL statements' rather 19 | than worry about how to properly configure cache instances or about duplicating 20 | current connections to the database. 21 | 22 | .. seealso:: 23 | 24 | `Prepared statements `_ 25 | 26 | One of the main goals of **DALMP** is to avoid complexity at all cost without 27 | losing flexibility and performance. The main class uses the PHP 28 | `mysqli extension `_, therefore there is not need 29 | to have the `PDO `_ extension (older version of PHP didn't include PDO by default). 30 | 31 | To take advantage of the cache class and methods it is suggested to install the 32 | following extensions: 33 | 34 | * redis: `http://github.com/nicolasff/phpredis `_ 35 | * memcache: `http://pecl.php.net/package/memcache `_ 36 | 37 | .. seealso:: 38 | 39 | `Dalmp\\Cache `_ 40 | 41 | If you have a site on the cloud or in a load balanced enviroment, you could 42 | take advantege of how **DALMP** handle `sessions `_ by storing them in a database or in 43 | a cache engine. 44 | 45 | 46 | .. seealso:: 47 | 48 | `Dalmp\\Sessions `_ 49 | 50 | 51 | 52 | On `FreeBSD `_ you can install **DALMP** from ports: /usr/ports/databases/dalmp. 53 | -------------------------------------------------------------------------------- /docs/cache.rst: -------------------------------------------------------------------------------- 1 | DALMP\\Cache 2 | ============ 3 | 4 | 5 | The ``DALMP\Cache`` class works as a dispatcher for the current Cache classes, following a common interface in order to maintain 6 | compatibility with other **DALMP** classes. 7 | 8 | *Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.* 9 | 10 | .. seealso:: 11 | 12 | `PHP Object Interfaces `_. 13 | 14 | 15 | **Parameters** 16 | 17 | :: 18 | 19 | DALMP\Cache(object) 20 | 21 | :object: An `CacheInterface instance `_. 22 | 23 | **Example** 24 | 25 | .. code-block:: php 26 | :linenos: 27 | :emphasize-lines: 12, 14 28 | 29 | useCache($cache); 43 | 44 | $rs = $db->CacheGetOne('SELECT now()'); 45 | 46 | echo $rs, PHP_EOL; 47 | 48 | 49 | **See also** 50 | 51 | .. toctree:: 52 | :maxdepth: 2 53 | 54 | cache/CacheInterface 55 | cache/APC 56 | cache/disk 57 | cache/memcache 58 | cache/redis 59 | 60 | .. note:: 61 | 62 | The **Dalmp\\Cache** has no dependency with the `DALMP\\Database `_ class, this means that you can use only the Database or the Cache classes with out need to depend on eitherone. 63 | -------------------------------------------------------------------------------- /docs/cache/APC.rst: -------------------------------------------------------------------------------- 1 | APC 2 | === 3 | 4 | Implements the ``CacheInteface`` using as APC as the cache backend. 5 | 6 | Requires `APC PECL extension `_. 7 | -------------------------------------------------------------------------------- /docs/cache/CacheInterface.rst: -------------------------------------------------------------------------------- 1 | CacheInterface 2 | ============== 3 | 4 | ``CacheInterface`` is **DALMP** interface to be use with the `DALMP\\Cache `_ class. 5 | 6 | 7 | The common methods are: 8 | 9 | =========================== ======================================= 10 | Method Description 11 | =========================== ======================================= 12 | Delete($key) Delete item from the server. 13 | Flush() Flush all existing items at the server. 14 | Get($key) Retrieve item from the server. 15 | Set($key, $value, $ttl = 0) Store data at the server. 16 | Stats() Get statistics of the server. 17 | X() Return the cache object. 18 | =========================== ======================================= 19 | 20 | 21 | All the cache backends must implement this `interface `_ in order to properly work with **DALMP**. 22 | 23 | __construct 24 | ........... 25 | 26 | The construct for each cache backend maybe be different and it is used for 27 | defining specific options like the host, port, path, etc. 28 | 29 | .. seealso:: 30 | 31 | `PHP Object Interfaces `_. 32 | -------------------------------------------------------------------------------- /docs/cache/disk.rst: -------------------------------------------------------------------------------- 1 | Disk 2 | ==== 3 | 4 | Implements the ``CacheInteface`` using as the hard disk as the cache backend. 5 | 6 | 7 | __construct 8 | ........... 9 | 10 | :: 11 | 12 | __construct($path) 13 | 14 | :$path: Directory to store the cache files - default ``/tmp/dalmp_cache``. 15 | 16 | Constants 17 | ......... 18 | 19 | :: 20 | 21 | define('DALMP_CACHE_DIR', '/tmp/dalmp/cache/'); 22 | 23 | Defines where to store the cache when using 'dir' cache type. 24 | 25 | This means that if no $path is passed as an argument to the **__construct** 26 | before using the default value will try to get a path from the **DALMP_CACHE_DIR** 27 | constant if set. 28 | 29 | Example 30 | ....... 31 | 32 | .. code-block:: php 33 | :linenos: 34 | :emphasize-lines: 5 35 | 36 | set('mykey', 'xpto', 300); 43 | 44 | $cache->get('mykey'); 45 | 46 | $cache->stats(); 47 | 48 | 49 | .. seealso:: 50 | 51 | `Cache Examples `_. 52 | -------------------------------------------------------------------------------- /docs/cache/memcache.rst: -------------------------------------------------------------------------------- 1 | Memcache 2 | ======== 3 | 4 | Implements the ``CacheInteface`` using `memcached ` as the cache backend. 5 | 6 | Requires `Memcache PECL extension `_. 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct($host, $port, $timeout, $compress) 14 | 15 | :$host: Point to the host where memcache is listening for connections. This parameter may also specify other transports like unix:///path/to/memcache.sock to use UNIX domain sockets - default 127.0.0.1. 16 | :$port: Point to the port where memcache is listening for connections - default 11211. 17 | :$timeout: Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. 18 | :$compress: Enables or disables (true/false) payload compression, Use `MEMCACHE_COMPRESSED `_ to store the item compressed (uses zlib) - default false. 19 | 20 | 21 | 22 | Example 23 | ....... 24 | 25 | .. code-block:: php 26 | :linenos: 27 | :emphasize-lines: 5 28 | 29 | set('mykey', 'xpto', 300); 36 | 37 | $cache->get('mykey'); 38 | 39 | $cache->X()->replace('mykey', 'otpx', false, 300); 40 | 41 | 42 | .. seealso:: 43 | 44 | `Cache Examples `_. 45 | -------------------------------------------------------------------------------- /docs/cache/redis.rst: -------------------------------------------------------------------------------- 1 | Redis 2 | ===== 3 | 4 | Implements the ``CacheInteface`` using as `redis.io `_. 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct($host, $port, $timeout) 14 | 15 | :$host: Point to the host where redis is listening for connections. This parameter may also specify other transports like unix:///path/to/redis.sock to use UNIX domain sockets - default 127.0.0.1. 16 | :$port: Point to the port where redis is listening for connections - default 6379. 17 | :$timeout: Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. 18 | 19 | Example 20 | ....... 21 | 22 | .. code-block:: php 23 | :linenos: 24 | :emphasize-lines: 5 25 | 26 | set('mykey', 'xpto', 300); 33 | 34 | $cache->get('mykey'); 35 | 36 | $cache->X()->HSET('myhash', 'field1', 'hello'): 37 | 38 | $cache->X()->HGET('myhash', 'field1'); 39 | 40 | $cache->X()->HGETALL('myhash'); 41 | 42 | 43 | .. seealso:: 44 | 45 | `Cache Examples `_. 46 | -------------------------------------------------------------------------------- /docs/database.rst: -------------------------------------------------------------------------------- 1 | DALMP\\Database 2 | =============== 3 | 4 | The ``DALMP\Database`` class contains a set of `methods `_ that allow to query a 5 | database in a more easy and secure way. 6 | 7 | The next table contains, 5 common methods for retrieving data: 8 | 9 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 10 | | Name | Normal | Prepared Statements | Cache Normal | Cache Prepared Statements | 11 | +======+=================================================+=====================+===============+===========================+ 12 | | all | `GetAll `_ | PGetAll | CacheGetAll | CachePGetAll | 13 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 14 | | assoc| `GetAssoc `_ | PGetAssoc | CacheGetAssoc | CachePGetAssoc | 15 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 16 | | col | `GetCol `_ | PGetCol | CacheGetCol | CachePGetCol | 17 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 18 | | one | `GetOne `_ | PGetOne | CacheGetOne | CachePGetOne | 19 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 20 | | row | `GetRow `_ | PGetRow | CacheGetRow | CachePGetRow | 21 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 22 | 23 | .. seealso:: 24 | 25 | `DALMP\\Cache `_ 26 | 27 | 28 | Any query or either for Inserting or Updating: 29 | 30 | ======= ============================================= =================== 31 | Name Normal Prepared statements 32 | ======= ============================================= =================== 33 | Execute `Execute `_ PExecute 34 | ======= ============================================= =================== 35 | 36 | 37 | 38 | .. seealso:: 39 | 40 | `Prepared statements `_ 41 | 42 | 43 | The available methods are: 44 | 45 | .. toctree:: 46 | :maxdepth: 2 47 | 48 | database/AutoExecute 49 | database/Cache 50 | database/CacheFlush 51 | database/Close 52 | database/CompleteTrans 53 | database/construct 54 | database/csv 55 | database/debug 56 | database/ErrorMsg 57 | database/ErrorNum 58 | database/Execute 59 | database/FetchMode 60 | database/forceTruncate 61 | database/getAll 62 | database/getASSOC 63 | database/getCol 64 | database/getOne 65 | database/getRow 66 | database/getClientVersion 67 | database/getColumnNames 68 | database/getNumOfFields 69 | database/getNumOfRows 70 | database/getNumOfRowsAffected 71 | database/getServerVersion 72 | database/Insert_Id 73 | database/isConnected 74 | database/map 75 | database/multipleInsert 76 | database/PClose 77 | database/PExecute 78 | database/PQuery 79 | database/Prepare 80 | database/qstr 81 | database/query 82 | database/renumber 83 | database/RollBackTrans 84 | database/StartTrans 85 | database/useCache 86 | database/UUID 87 | database/X 88 | -------------------------------------------------------------------------------- /docs/database/AutoExecute.rst: -------------------------------------------------------------------------------- 1 | AutoExecute 2 | =========== 3 | 4 | Automatically prepares and runs an INSERT or UPDATE query based on variables 5 | you supply. 6 | 7 | This is very usefull when you simple want to save post data from a huge web 8 | form, AutoExecute will genereate a mysql prepared statement from the array used 9 | and INSERT or UPDATE 10 | 11 | Parameters 12 | .......... 13 | 14 | :: 15 | 16 | AutoExecute($table, $fields, $mode = 'INSERT', $where = null) 17 | 18 | :$table: The name of the table you want to INSERT or UPDATE 19 | 20 | :$fields: An assoc array (key => value), keys are fields names, values are values of these fields. 21 | 22 | :$mode: INSERT or UPDATE 23 | 24 | :$where: A string to be used in the WHERE clause. This is only used when $mode = UPDATE. 25 | 26 | 27 | Examples 28 | ........ 29 | 30 | 31 | Insert all `$_POST `_ data example: 32 | 33 | .. code-block:: php 34 | :linenos: 35 | :emphasize-lines: 13 36 | 37 | AutoExecute('mytable', $_POST); 50 | 51 | 52 | Update example: 53 | 54 | .. code-block:: php 55 | :linenos: 56 | :emphasize-lines: 15 57 | 58 | 'nbari', 70 | 'status' => 1); 71 | 72 | $db->AutoExecute('mytable', $data, 'UPDATE', 'status=0 AND uid=14'); -------------------------------------------------------------------------------- /docs/database/CacheFlush.rst: -------------------------------------------------------------------------------- 1 | CacheFlush 2 | ========== 3 | 4 | Flush the cache, if no parameter specified it will flush all the cache. 5 | 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | CacheFlush(sql or group, $key=null) 13 | 14 | :sql or group: The query to flush or the group name. 15 | :$key: The custom key assigned to the query. 16 | 17 | 18 | To flush / empty all the cache just call the CacheFlush with no parameteres, 19 | example:: 20 | 21 | $db->CacheFlush(); 22 | 23 | Examples 24 | ........ 25 | 26 | Flush a query: 27 | 28 | .. code-block:: php 29 | :linenos: 30 | :emphasize-lines: 17 31 | 32 | FetchMode('ASSOC'); 44 | 45 | $rs = $db->CacheGetAll(300, 'SELECT * FROM City'); 46 | 47 | // To flush the query 48 | $db->CacheFlush('SELECT * FROM City'); 49 | 50 | 51 | Flush a query with a custom key: 52 | 53 | .. code-block:: php 54 | :linenos: 55 | :emphasize-lines: 5 56 | 57 | CacheGetAll(300, 'SELECT * FROM City', 'my_custom_key'); 60 | 61 | $db->CacheFlush('SELECT * FROM City', 'my_custom_key'); 62 | 63 | 64 | Flushing a chached group: 65 | 66 | .. code-block:: php 67 | :linenos: 68 | :emphasize-lines: 7 69 | 70 | CachePGetAll('SELECT * FROM Country WHERE Population <= ?', 100000, 'group:B'); 73 | $rs = $db->CachePGetAll(86400, 'SELECT * FROM Country WHERE Continent = ?', 'Europe', 'group:B'); 74 | 75 | // To flush all the group 76 | $db->CacheFlush('group:B'); -------------------------------------------------------------------------------- /docs/database/Close.rst: -------------------------------------------------------------------------------- 1 | Close 2 | ===== 3 | 4 | Closes a previously opened database connection, you normally not need to call 5 | this method, since DALMP when finishes automatically close all opening 6 | connections. -------------------------------------------------------------------------------- /docs/database/CompleteTrans.rst: -------------------------------------------------------------------------------- 1 | CompleteTrans 2 | ============= 3 | 4 | Complete the transaction, this must be used in conjunction with method 5 | `StartTrans `_. 6 | 7 | If success returns **true**, otherwise **false**. 8 | 9 | Example 10 | ....... 11 | 12 | .. code-block:: php 13 | :linenos: 14 | :emphasize-lines: 29, 30, 31, 33 15 | 16 | Execute('CREATE TABLE IF NOT EXISTS t_test (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB'); 28 | $db->Execute('TRUNCATE TABLE t_test'); 29 | $db->FetchMode('ASSOC'); 30 | 31 | $db->StartTrans(); 32 | $db->Execute('INSERT INTO t_test VALUES(1)'); 33 | $db->StartTrans(); 34 | $db->Execute('INSERT INTO t_test VALUES(2)'); 35 | print_r($db->GetAll('SELECT * FROM t_test')); 36 | $db->StartTrans(); 37 | $db->Execute('INSERT INTO t_test VALUES(3)'); 38 | print_r($db->GetAll('SELECT * FROM t_test')); 39 | $db->StartTrans(); 40 | $db->Execute('INSERT INTO t_test VALUES(7)'); 41 | print_r($db->GetALL('SELECT * FROM t_test')); 42 | $db->RollBackTrans(); 43 | print_r($db->GetALL('SELECT * FROM t_test')); 44 | $db->CompleteTrans(); 45 | $db->CompleteTrans(); 46 | $db->CompleteTrans(); 47 | 48 | if ($db->CompleteTrans()) { 49 | // your code 50 | } 51 | 52 | 53 | .. seealso:: 54 | 55 | `StartTrans `_ -------------------------------------------------------------------------------- /docs/database/ErrorMsg.rst: -------------------------------------------------------------------------------- 1 | ErrorMsg 2 | ======== 3 | 4 | Returns a string description of the last error. 5 | 6 | Example 7 | ....... 8 | 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 16 13 | 14 | Execute('SET a=1'); 27 | } catch (Exception $d) { 28 | // Errormessage: Unknown system variable 'a' 29 | printf("Errormessage: %s\n", $db->ErrorMsg()); 30 | } -------------------------------------------------------------------------------- /docs/database/ErrorNum.rst: -------------------------------------------------------------------------------- 1 | ErrorNum 2 | ======== 3 | 4 | Returns the error code for the most recent function call. 5 | 6 | Example 7 | ....... 8 | 9 | .. code-block:: php 10 | :linenos: 11 | :emphasize-lines: 16 12 | 13 | Execute('SET a=1'); 26 | } catch (Exception $d) { 27 | // Errormessage: 1193 28 | printf("Errormessage: %s\n", $db->ErrorNum()); 29 | } -------------------------------------------------------------------------------- /docs/database/Execute.rst: -------------------------------------------------------------------------------- 1 | Execute 2 | ======= 3 | 4 | Execute an SQL statement, returns true on success, false if there was an error 5 | in executing the sql. 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | Execute($sql) 13 | 14 | :$sql: The MySQL query to perform on the database. 15 | 16 | In most cases you only use this method when Inserting or Updating data, for 17 | retrieving data the 5 common methods are: 18 | 19 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 20 | | Name | Normal | Prepared Statements | Cache Normal | Cache Prepared Statements | 21 | +======+=================================================+=====================+===============+===========================+ 22 | | all | `GetAll `_ | PGetAll | CacheGetAll | CachePGetAll | 23 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 24 | | assoc| `GetAssoc `_ | PGetAssoc | CacheGetAssoc | CachePGetAssoc | 25 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 26 | | col | `GetCol `_ | PGetCol | CacheGetCol | CachePGetCol | 27 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 28 | | one | `GetOne `_ | PGetOne | CacheGetOne | CachePGetOne | 29 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 30 | | row | `GetRow `_ | PGetRow | CacheGetRow | CachePGetRow | 31 | +------+-------------------------------------------------+---------------------+---------------+---------------------------+ 32 | 33 | .. seealso:: 34 | 35 | `Prepared statements `_ & `PExecute `_. 36 | 37 | 38 | Examples 39 | ........ 40 | 41 | 42 | .. code-block:: php 43 | :linenos: 44 | :emphasize-lines: 12 45 | 46 | Execute("INSERT INTO table (name,email,age) VALUES('name', 'email', 70)"); 58 | 59 | 60 | You can also catch exception and continue execution: 61 | 62 | .. code-block:: php 63 | :linenos: 64 | :emphasize-lines: 13, 18 65 | 66 | Execute('CREATE TABLE myCity LIKE City'); 79 | } catch (Exception $e) { 80 | echo "Table already exists.",$db->isCli(1); 81 | } 82 | 83 | $db->Execute("INSERT INTO myCity VALUES (NULL, 'Toluca', 'MEX', 'México', 467713)"); -------------------------------------------------------------------------------- /docs/database/Insert_Id.rst: -------------------------------------------------------------------------------- 1 | Insert_Id 2 | ========= 3 | 4 | Returns the auto generated id used in the last query. 5 | 6 | Example 7 | ....... 8 | 9 | .. code-block:: php 10 | :linenos: 11 | :emphasize-lines: 19 12 | 13 | Execute('CREATE TABLE myCity LIKE City'); 26 | } catch (Exception $e) { 27 | echo "Table already exists.",$db->isCli(1); 28 | } 29 | 30 | $db->Execute("INSERT INTO myCity VALUES (NULL, 'Toluca', 'MEX', 'México', 467713)"); 31 | printf ("New Record has id %d.\n", $db->Insert_id()); -------------------------------------------------------------------------------- /docs/database/PClose.rst: -------------------------------------------------------------------------------- 1 | PClose 2 | ====== 3 | 4 | Closes a previously opened database connection, you normally not need to call 5 | this method, since DALMP when finishes automatically close all opening 6 | connections. -------------------------------------------------------------------------------- /docs/database/PExecute.rst: -------------------------------------------------------------------------------- 1 | PExecute 2 | ======== 3 | 4 | Execute an SQL statement using `Prepared Statements `_. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | PExecute($sql, $varN) 12 | 13 | :$sql: The MySQL query to perform on the database 14 | :$varN: The variable(s) that will be placed instead of the **?** placeholder separated by a ',' or it can be the method `Prepare `_. 15 | 16 | 17 | .. seealso:: 18 | 19 | `SQL syntax prepared statements `_. 20 | 21 | 22 | Like the `Execute `_ Method, in most cases you 23 | probably only use this method when **Inserting** or **Updating** data for retrieving 24 | data you can use: 25 | 26 | ================== ========================================================================================= 27 | method Description 28 | ================== ========================================================================================= 29 | **P**\ `getAll`_ Executes the SQL and returns the all the rows as a 2-dimensional array. 30 | **P**\ `getRow`_ Executes the SQL and returns the first row as an array. 31 | **P**\ `getCol`_ Executes the SQL and returns all elements of the first column as a 1-dimensional array. 32 | **P**\ `getOne`_ Executes the SQL and returns the first field of the first row. 33 | **P**\ `getASSOC`_ Executes the SQL and returns an associative array for the given query. \ 34 | If the number of columns returned is greater to two, a 2-dimensional array is returned\ 35 | with the first column of the recordset becomes the keys to the rest of the rows. \ 36 | If the columns is equal to two, a 1-dimensional array is created, where the the keys \ 37 | directly map to the values. 38 | ================== ========================================================================================= 39 | 40 | .. _getAll: /en/latest/database/getAll.html 41 | .. _getASSOC: /en/latest/database/getASSOC.html 42 | .. _getCol: /en/latest/database/getCol.html 43 | .. _getOne: /en/latest/database/getOne.html 44 | .. _getRow: /en/latest/database/getRow.html 45 | 46 | .. note:: 47 | 48 | Notice that when using "Prepared statements" the methods are 49 | prefixed with a **P**. 50 | 51 | 52 | Examples 53 | ........ 54 | 55 | .. code-block:: php 56 | :linenos: 57 | :emphasize-lines: 12 58 | 59 | PExecute('SET time_zone=?', 'UTC'); 71 | 72 | 73 | An Insert example: 74 | 75 | .. code-block:: php 76 | :linenos: 77 | 78 | PExecute('INSERT INTO mytable (colA, colB) VALUES(?, ?)', rand(), rand()); 81 | 82 | 83 | An Update example: 84 | 85 | .. code-block:: php 86 | :linenos: 87 | 88 | PExecute('UPDATE Country SET code=? WHERE Code=?', 'PRT', 'PRT'); 91 | 92 | .. warning:: 93 | 94 | When updating the return value **0**, Zero indicates that no records where 95 | updated. -------------------------------------------------------------------------------- /docs/database/PQuery.rst: -------------------------------------------------------------------------------- 1 | Pquery 2 | ====== 3 | 4 | Prepared Statements query. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | Pquery($out = array()) 12 | 13 | :$out: An empty array that will contain the output. 14 | 15 | 16 | This method is useful, in cases where you need to process each row of a query 17 | without consuming too much memory. 18 | 19 | 20 | Example 21 | ....... 22 | 23 | .. code-block:: php 24 | :linenos: 25 | :emphasize-lines: 14,15 26 | 27 | PExecute('SELECT * FROM Country WHERE Continent = ?', 'Europe'); 39 | 40 | $out = array(); 41 | while ($rows = $db->Pquery($out)) { 42 | print_r($out); 43 | } -------------------------------------------------------------------------------- /docs/database/Prepare.rst: -------------------------------------------------------------------------------- 1 | Prepare 2 | ======= 3 | 4 | Prepare arguments for the Prepared Statements `PExecute `_ method. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | Prepare($arg= null) 12 | 13 | :$arg: Argument to be used in the PExecute method, if no input it will return the array with the prepared statements. 14 | 15 | The prepare method automatically detect the input type, you can also override 16 | this, using something like:: 17 | 18 | Prepare('s','1e1') 19 | 20 | Example 21 | ....... 22 | 23 | Building dynamic queries that require prepared statements: 24 | 25 | .. code-block:: php 26 | :linenos: 27 | :emphasize-lines: 11, 16, 20, 29 28 | 29 | Prepare($id) 40 | 41 | $sql = 'SELECT * FROM test WHERE id=?'; 42 | 43 | if ($x == 3) { 44 | $db->Prepare($x); 45 | $sql .= 'AND id !=?'; 46 | } 47 | 48 | $db->Prepare('s', 'colb'); 49 | 50 | $sql .= 'AND colB=?'; 51 | 52 | /** 53 | * this will produce a query like: 54 | * SELECT * FROM test WHERE id=? AND id !=? AND colB=? 55 | * with params = ["iis",1,3,"colb"] 56 | */ 57 | $rs = $db->PgetAll($sql, $db->Prepare()); 58 | 59 | 60 | .. seealso :: 61 | 62 | `Prepared statements `_ -------------------------------------------------------------------------------- /docs/database/RollBackTrans.rst: -------------------------------------------------------------------------------- 1 | RollBackTrans 2 | ============= 3 | 4 | Rollback the transaction, this must be used in conjunction with method 5 | `StartTrans `_. 6 | 7 | returns false if there was an error executing the ROLLBACK. 8 | 9 | Example 10 | ....... 11 | 12 | .. code-block:: php 13 | :linenos: 14 | :emphasize-lines: 27 15 | 16 | Execute('CREATE TABLE IF NOT EXISTS t_test (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB'); 28 | $db->Execute('TRUNCATE TABLE t_test'); 29 | $db->FetchMode('ASSOC'); 30 | 31 | $db->StartTrans(); 32 | $db->Execute('INSERT INTO t_test VALUES(1)'); 33 | $db->StartTrans(); 34 | $db->Execute('INSERT INTO t_test VALUES(2)'); 35 | print_r($db->GetAll('SELECT * FROM t_test')); 36 | $db->StartTrans(); 37 | $db->Execute('INSERT INTO t_test VALUES(3)'); 38 | print_r($db->GetAll('SELECT * FROM t_test')); 39 | $db->StartTrans(); 40 | $db->Execute('INSERT INTO t_test VALUES(7)'); 41 | print_r($db->GetALL('SELECT * FROM t_test')); 42 | $db->RollBackTrans(); 43 | print_r($db->GetALL('SELECT * FROM t_test')); 44 | $db->CompleteTrans(); 45 | $db->CompleteTrans(); 46 | $db->CompleteTrans(); 47 | 48 | if ($db->CompleteTrans()) { 49 | // your code 50 | } 51 | 52 | 53 | .. seealso:: 54 | 55 | `StartTrans `_ -------------------------------------------------------------------------------- /docs/database/StartTrans.rst: -------------------------------------------------------------------------------- 1 | StartTrans 2 | ========== 3 | 4 | Start the transaction, for this the mysql table must be of type `InnoDB `_. 5 | 6 | Example 7 | ....... 8 | 9 | .. code-block:: php 10 | :linenos: 11 | :emphasize-lines: 16, 18, 21, 24 12 | 13 | Execute('CREATE TABLE IF NOT EXISTS t_test (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB'); 25 | $db->Execute('TRUNCATE TABLE t_test'); 26 | $db->FetchMode('ASSOC'); 27 | 28 | $db->StartTrans(); 29 | $db->Execute('INSERT INTO t_test VALUES(1)'); 30 | $db->StartTrans(); 31 | $db->Execute('INSERT INTO t_test VALUES(2)'); 32 | print_r($db->GetAll('SELECT * FROM t_test')); 33 | $db->StartTrans(); 34 | $db->Execute('INSERT INTO t_test VALUES(3)'); 35 | print_r($db->GetAll('SELECT * FROM t_test')); 36 | $db->StartTrans(); 37 | $db->Execute('INSERT INTO t_test VALUES(7)'); 38 | print_r($db->GetALL('SELECT * FROM t_test')); 39 | $db->RollBackTrans(); 40 | print_r($db->GetALL('SELECT * FROM t_test')); 41 | $db->CompleteTrans(); 42 | $db->CompleteTrans(); 43 | $db->CompleteTrans(); 44 | 45 | if ($db->CompleteTrans()) { 46 | // your code 47 | } 48 | 49 | 50 | .. seealso:: 51 | 52 | `CompleteTrans `_, `MySQL START 53 | TRANSACTION, COMMIT and ROLLBACK Syntax `_. -------------------------------------------------------------------------------- /docs/database/UUID.rst: -------------------------------------------------------------------------------- 1 | UUID 2 | ==== 3 | 4 | Generates an Universally Unique Identifier (`UUID `_) v4. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | UUID($b=null) 12 | 13 | :$b: If true will return the UUID in binary, removing the dashes so that you can store it on a DB using column data type binary(16). 14 | 15 | Examples 16 | ........ 17 | 18 | .. code-block:: php 19 | :linenos: 20 | 21 | UUID(); 25 | 26 | echo $db->UUID(true); 27 | 28 | 29 | Example storing UUID as binary(16): 30 | 31 | .. code-block:: php 32 | :linenos: 33 | :emphasize-lines: 12 34 | 35 | UUID(); 47 | 48 | $db->PExecute("INSERT INTO table (post, uuid) VALUES(?, UNHEX(REPLACE(?, '-', '')))", json_encode($_POST), $uuid); 49 | 50 | 51 | Example converting from binary(16) to original UUID format chat(36): 52 | 53 | .. code-block:: php 54 | :linenos: 55 | :emphasize-lines: 12 56 | 57 | FetchMode('ASSOC')->getCol($sql); 71 | 72 | 73 | .. seealso:: 74 | 75 | `MySQL string functions `_. -------------------------------------------------------------------------------- /docs/database/X.rst: -------------------------------------------------------------------------------- 1 | X 2 | = 3 | 4 | Returns the `mysqli `_ object. 5 | 6 | Example 7 | ....... 8 | 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 12,13 13 | 14 | X()->ping(); 26 | $db->X()->stat(); 27 | 28 | $rs = $db->GetOne('SELECT DATABASE()'); 29 | echo $rs, PHP_EOL; 30 | 31 | $db->X()->select_db('mysql'); 32 | 33 | $rs = $db->GetOne('SELECT DATABASE()'); 34 | echo $rs, PHP_EOL; 35 | 36 | 37 | 38 | .. seealso:: 39 | 40 | `class.mysqli.php `_, `ping `_, `stat `_. -------------------------------------------------------------------------------- /docs/database/construct.rst: -------------------------------------------------------------------------------- 1 | __construct 2 | =========== 3 | 4 | 5 | ``DALMP\Database`` takes the parameters from a `DNS `_ (database source name) so 6 | before you can start using it you need to define this values. 7 | 8 | DSN format 9 | .......... 10 | 11 | .. code-block:: rest 12 | 13 | charset://username:password@host:port/database 14 | 15 | When using `Unix domain sockets `_:: 16 | 17 | charset://username:password@unix_socket=\path\of\the.socket/database 18 | 19 | * Notice that the path of the socket is using backslashes. 20 | 21 | :: 22 | 23 | \path\of\the.socket 24 | 25 | Will be translated to:: 26 | 27 | /path/of/the.socket 28 | 29 | 30 | .. seealso:: 31 | 32 | `Unix sockets vs Internet sockets `_ 33 | 34 | 35 | 36 | Examples 37 | ........ 38 | 39 | .. sidebar:: DSN values 40 | 41 | :charset: utf8 42 | :user: $user 43 | :password: $password 44 | :host: 127.0.0.1 45 | :database: test 46 | 47 | .. code-block:: php 48 | :linenos: 49 | :emphasize-lines: 8 50 | 51 | getOne('SELECT now()'); 64 | } catch (\Exception $e) { 65 | print_r($e->getMessage()); 66 | } 67 | 68 | /** 69 | * 1 log to single file 70 | * 2 log to multiple files (creates a log per request) 71 | * 'off' to stop debuging 72 | */ 73 | $db->debug(1); 74 | 75 | echo $db, PHP_EOL; // print connection details 76 | 77 | If you wan to use the system default charset the DSN would be: 78 | 79 | .. code-block:: php 80 | :linenos: 81 | 82 | $DSN = "mysql://$user:$password@127.0.0.1/test"; 83 | 84 | * notice the **mysql://** instead of the **utf8://** 85 | 86 | 87 | .. seealso:: 88 | 89 | `Quickstart `_. -------------------------------------------------------------------------------- /docs/database/csv.rst: -------------------------------------------------------------------------------- 1 | csv 2 | === 3 | 4 | This method exports your results in CSV 5 | (`Comma Separated Values `_). 6 | 7 | 8 | Parameters 9 | .......... 10 | 11 | :: 12 | 13 | csv($sql) 14 | 15 | :$sql: Your normal sql or either a prepared statement query. 16 | 17 | :returns: CVS. 18 | 19 | Example 20 | ....... 21 | 22 | Serve a CSV file: 23 | 24 | .. code-block:: php 25 | :linenos: 26 | :emphasize-lines: 17 27 | 28 | csv('SELECT row1, row2, row3, row4 FROM table WHERE uid=? AND cat=?', 3, 'oi'); -------------------------------------------------------------------------------- /docs/database/debug.rst: -------------------------------------------------------------------------------- 1 | debug 2 | ===== 3 | 4 | This method will enable debugging, so that you can trace your full queries. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | debug($log2file = false, $debugFile = false) 12 | 13 | 14 | :$log2file: When set to **1**, log is written to a single file, if **2** it creates multiple log files per request so that you can do a more intense debugging, **off** stop debuging. 15 | 16 | :$debugFile: Path of the file to write logs, defaults to ``/tmp/dalmp.log`` 17 | 18 | 19 | Constants 20 | ......... 21 | 22 | :: 23 | 24 | define('DALMP_DEBUG_FILE', '/home/tmp/debug.log'); 25 | 26 | Defines where the debug file will be write to. 27 | 28 | 29 | Example 30 | ....... 31 | 32 | .. code-block:: php 33 | :linenos: 34 | :emphasize-lines: 17 35 | 36 | debug(1); 53 | 54 | try { 55 | $rs = $db->getOne('SELECT now()'); 56 | } catch (Exception $e) { 57 | print_r($e->getMessage()); 58 | } 59 | 60 | echo $db,PHP_EOL; // print connection details -------------------------------------------------------------------------------- /docs/database/fill.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | rst = [f for f in os.listdir('.') if f.endswith('rst')] 5 | 6 | for f in rst: 7 | name = f.split('.')[0] 8 | print name, len(name), f 9 | with open(f, 'w') as rst_file: 10 | rst_file.write("%s\n" % name) 11 | for x in range(len(name)): 12 | rst_file.write('=') 13 | rst_file.write("\n\nTodo") 14 | -------------------------------------------------------------------------------- /docs/database/forceTruncate.rst: -------------------------------------------------------------------------------- 1 | forceTruncate 2 | ============= 3 | 4 | Force truncate of a table either if are `InnoDB `_. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | forceTable($table) 12 | 13 | :$table: Name of the table to truncate. 14 | 15 | 16 | Example 17 | ....... 18 | 19 | .. code-block:: php 20 | :linenos: 21 | :emphasize-lines: 12 22 | 23 | forceTrucate('mytable'); -------------------------------------------------------------------------------- /docs/database/getASSOC.rst: -------------------------------------------------------------------------------- 1 | getASSOC / PgetASSOC 2 | ==================== 3 | 4 | Executes the SQL and returns an associative array for the given query. 5 | 6 | If the number of columns returned is greater to two, a 2-dimensional array is 7 | returned, with the first column of the recordset becomes the keys to the rest 8 | of the rows. If the columns is equal to two, a 1-dimensional array is created, 9 | where the the keys directly map to the values. 10 | 11 | If an error occurs, false is returned. 12 | 13 | 14 | Parameters 15 | .......... 16 | 17 | :: 18 | 19 | getASSOC($sql) 20 | 21 | :$sql: The MySQL query to perfom on the database. 22 | 23 | Prepared statements Parameters 24 | .............................. 25 | 26 | :: 27 | 28 | PgetASSOC($sql, $varN) 29 | 30 | :$sql: The MySQL query to perfom on the database 31 | :$varN: The variable(s) that will be placed instead of the **?** placeholder separated by a ',' or it can be the method `Prepare `_. 32 | 33 | Example 34 | ....... 35 | 36 | .. code-block:: php 37 | :linenos: 38 | :emphasize-lines: 12 39 | 40 | PGetASSOC('SELECT name, continent FROM Country WHERE Region = ?', 'Caribbean'); 52 | 53 | Output of ``print_r($rs)``: 54 | 55 | .. code-block:: rest 56 | :linenos: 57 | 58 | Array 59 | ( 60 | [Aruba] => North America 61 | [Anguilla] => North America 62 | [Netherlands Antilles] => North America 63 | [Antigua and Barbuda] => North America 64 | [Bahamas] => North America 65 | [Barbados] => North America 66 | [Cuba] => North America 67 | [Cayman Islands] => North America 68 | [Dominica] => North America 69 | [Dominican Republic] => North America 70 | [Guadeloupe] => North America 71 | [Grenada] => North America 72 | [Haiti] => North America 73 | [Jamaica] => North America 74 | [Saint Kitts and Nevis] => North America 75 | [Saint Lucia] => North America 76 | [Montserrat] => North America 77 | [Martinique] => North America 78 | [Puerto Rico] => North America 79 | [Turks and Caicos Islands] => North America 80 | [Trinidad and Tobago] => North America 81 | [Saint Vincent and the Grenadines] => North America 82 | [Virgin Islands, British] => North America 83 | [Virgin Islands, U.S.] => North America 84 | ) -------------------------------------------------------------------------------- /docs/database/getClientVersion.rst: -------------------------------------------------------------------------------- 1 | getClientVersion 2 | ================ 3 | 4 | 5 | Returns client version number as an integer. 6 | 7 | Example 8 | ....... 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 12 13 | 14 | getClientVersion(); -------------------------------------------------------------------------------- /docs/database/getCol.rst: -------------------------------------------------------------------------------- 1 | getCol / PgetCol 2 | ================ 3 | 4 | Executes the SQL and returns all elements of the first column as a 5 | 1-dimensional array. 6 | 7 | If an error occurs, false is returned. 8 | 9 | Parameters 10 | .......... 11 | 12 | :: 13 | 14 | getCol($sql) 15 | 16 | :$sql: The MySQL query to perfom on the database. 17 | 18 | Prepared statements Parameters 19 | .............................. 20 | 21 | :: 22 | 23 | PgetCol($sql, $varN) 24 | 25 | :$sql: The MySQL query to perfom on the database 26 | :$varN: The variable(s) that will be placed instead of the **?** placeholder separated by a ',' or it can be the method `Prepare `_. 27 | 28 | Example 29 | ....... 30 | 31 | .. code-block:: php 32 | :linenos: 33 | :emphasize-lines: 15, 20 34 | 35 | PGetCol('SELECT name FROM Country WHERE Region = ?', 'Caribbean'); 47 | 48 | Output of ``print_r($rs)``: 49 | 50 | .. code-block:: rest 51 | :linenos: 52 | 53 | Array 54 | ( 55 | [0] => Aruba 56 | [1] => Anguilla 57 | [2] => Netherlands Antilles 58 | [3] => Antigua and Barbuda 59 | [4] => Bahamas 60 | [5] => Barbados 61 | [6] => Cuba 62 | [7] => Cayman Islands 63 | [8] => Dominica 64 | [9] => Dominican Republic 65 | [10] => Guadeloupe 66 | [11] => Grenada 67 | [12] => Haiti 68 | [13] => Jamaica 69 | [14] => Saint Kitts and Nevis 70 | [15] => Saint Lucia 71 | [16] => Montserrat 72 | [17] => Martinique 73 | [18] => Puerto Rico 74 | [19] => Turks and Caicos Islands 75 | [20] => Trinidad and Tobago 76 | [21] => Saint Vincent and the Grenadines 77 | [22] => Virgin Islands, British 78 | [23] => Virgin Islands, U.S. 79 | ) -------------------------------------------------------------------------------- /docs/database/getColumnNames.rst: -------------------------------------------------------------------------------- 1 | getColumnNames 2 | ============== 3 | 4 | Return the name of the tables. 5 | 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | getColumnNames($tablename) 13 | 14 | :$tablename: Name of the table to get the column names. 15 | 16 | 17 | Example 18 | ....... 19 | 20 | .. code-block:: php 21 | :linenos: 22 | :emphasize-lines: 12 23 | 24 | getColumnNames(); 36 | 37 | // output of print_r($rs); 38 | Array 39 | ( 40 | [0] => Code 41 | [1] => Name 42 | [2] => Continent 43 | [3] => Region 44 | [4] => SurfaceArea 45 | [5] => IndepYear 46 | [6] => Population 47 | [7] => LifeExpectancy 48 | [8] => GNP 49 | [9] => GNPOld 50 | [10] => LocalName 51 | [11] => GovernmentForm 52 | [12] => HeadOfState 53 | [13] => Capital 54 | [14] => Code2 55 | ) -------------------------------------------------------------------------------- /docs/database/getNumOfFields.rst: -------------------------------------------------------------------------------- 1 | getNumOfFields 2 | ============== 3 | 4 | Returns the number of columns for the most recent query. 5 | 6 | 7 | Example 8 | ....... 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 34 13 | 14 | FetchMode('ASSOC')->PGetRow('SELECT * FROM Country WHERE Region = ? LIMIT 1', 'Caribbean'); 26 | 27 | // output of print_r($rs); 28 | Array 29 | ( 30 | [Code] => ABW 31 | [Name] => Aruba 32 | [Continent] => North America 33 | [Region] => Caribbean 34 | [SurfaceArea] => 193 35 | [IndepYear] => 36 | [Population] => 103000 37 | [LifeExpectancy] => 78.400001525879 38 | [GNP] => 828 39 | [GNPOld] => 793 40 | [LocalName] => Aruba 41 | [GovernmentForm] => Nonmetropolitan Territory of The Netherlands 42 | [HeadOfState] => Beatrix 43 | [Capital] => 129 44 | [Code2] => AW 45 | ) 46 | 47 | echo $db->getNumOfFields(); // return 15 -------------------------------------------------------------------------------- /docs/database/getNumOfRows.rst: -------------------------------------------------------------------------------- 1 | getNumOfRows 2 | ============ 3 | 4 | Returns the number of rows for the most recent query. 5 | 6 | 7 | Example 8 | ....... 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 34 13 | 14 | FetchMode('ASSOC')->PGetRow('SELECT * FROM Country WHERE Region = ? LIMIT 1', 'Caribbean'); 26 | 27 | // output of print_r($rs); 28 | Array 29 | ( 30 | [Code] => ABW 31 | [Name] => Aruba 32 | [Continent] => North America 33 | [Region] => Caribbean 34 | [SurfaceArea] => 193 35 | [IndepYear] => 36 | [Population] => 103000 37 | [LifeExpectancy] => 78.400001525879 38 | [GNP] => 828 39 | [GNPOld] => 793 40 | [LocalName] => Aruba 41 | [GovernmentForm] => Nonmetropolitan Territory of The Netherlands 42 | [HeadOfState] => Beatrix 43 | [Capital] => 129 44 | [Code2] => AW 45 | ) 46 | 47 | echo $db->getNumOfRows(); // return 1 -------------------------------------------------------------------------------- /docs/database/getNumOfRowsAffected.rst: -------------------------------------------------------------------------------- 1 | getNumOfRowsAffected 2 | ==================== 3 | 4 | Returns the total number of rows changed, deleted, or inserted by the last 5 | executed statement. -------------------------------------------------------------------------------- /docs/database/getOne.rst: -------------------------------------------------------------------------------- 1 | getOne / PGetOne 2 | ================ 3 | 4 | Executes the SQL and returns the first field of the first row. If an error 5 | occurs, false is returned. 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | getOne($sql) 13 | 14 | :$sql: The MySQL query to perfom on the database. 15 | 16 | Prepared statements Parameters 17 | .............................. 18 | 19 | :: 20 | 21 | PgetOne($sql, $varN) 22 | 23 | :$sql: The MySQL query to perfom on the database 24 | :$varN: The variable(s) that will be placed instead of the **?** placeholder separated by a ',' or it can be the method `Prepare `_. 25 | 26 | Example 27 | ....... 28 | 29 | .. code-block:: php 30 | :linenos: 31 | :emphasize-lines: 12 32 | 33 | PGetOne('SELECT * FROM Country WHERE Region = ? LIMIT 1', 'Caribbean'); 45 | 46 | Output of ``echo $rs``: 47 | 48 | .. code-block:: rest 49 | :linenos: 50 | 51 | Aruba -------------------------------------------------------------------------------- /docs/database/getRow.rst: -------------------------------------------------------------------------------- 1 | getRow / PgetRow 2 | ================ 3 | 4 | Executes the SQL and returns the first field of the first row. If an error 5 | occurs, false is returned. 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | getRow($sql) 13 | 14 | 15 | :$sql: The MySQL query to perfom on the database. 16 | 17 | Prepared statements Parameters 18 | .............................. 19 | 20 | :: 21 | 22 | PgetRow($sql, $varN) 23 | 24 | :$sql: The MySQL query to perfom on the database 25 | :$varN: The variable(s) that will be placed instead of the **?** placeholder separated by a ',' or it can be the method `Prepare `_. 26 | 27 | 28 | Example 29 | ....... 30 | 31 | .. code-block:: php 32 | :linenos: 33 | :emphasize-lines: 12 34 | 35 | PGetRow('SELECT * FROM Country WHERE Region = ? LIMIT 1', 'Caribbean'); 47 | 48 | Output of ``print_r($rs)``: 49 | 50 | .. code-block:: rest 51 | :linenos: 52 | 53 | Array 54 | ( 55 | [0] => ABW 56 | [Code] => ABW 57 | [1] => Aruba 58 | [Name] => Aruba 59 | [2] => North America 60 | [Continent] => North America 61 | [3] => Caribbean 62 | [Region] => Caribbean 63 | [4] => 193 64 | [SurfaceArea] => 193 65 | [5] => 66 | [IndepYear] => 67 | [6] => 103000 68 | [Population] => 103000 69 | [7] => 78.400001525879 70 | [LifeExpectancy] => 78.400001525879 71 | [8] => 828 72 | [GNP] => 828 73 | [9] => 793 74 | [GNPOld] => 793 75 | [10] => Aruba 76 | [LocalName] => Aruba 77 | [11] => Nonmetropolitan Territory of The Netherlands 78 | [GovernmentForm] => Nonmetropolitan Territory of The Netherlands 79 | [12] => Beatrix 80 | [HeadOfState] => Beatrix 81 | [13] => 129 82 | [Capital] => 129 83 | [14] => AW 84 | [Code2] => AW 85 | ) 86 | 87 | Same query but using FetchMode('ASSOC') 88 | 89 | .. code-block:: php 90 | :linenos: 91 | :emphasize-lines: 3 92 | 93 | FetchMode('ASSOC')->PGetRow('SELECT * FROM Country WHERE Region = ? LIMIT 1', 'Caribbean'); 96 | 97 | Output of ``print_r($rs)``: 98 | 99 | .. code-block:: rest 100 | :linenos: 101 | 102 | Array 103 | ( 104 | [Code] => ABW 105 | [Name] => Aruba 106 | [Continent] => North America 107 | [Region] => Caribbean 108 | [SurfaceArea] => 193 109 | [IndepYear] => 110 | [Population] => 103000 111 | [LifeExpectancy] => 78.400001525879 112 | [GNP] => 828 113 | [GNPOld] => 793 114 | [LocalName] => Aruba 115 | [GovernmentForm] => Nonmetropolitan Territory of The Netherlands 116 | [HeadOfState] => Beatrix 117 | [Capital] => 129 118 | [Code2] => AW 119 | ) -------------------------------------------------------------------------------- /docs/database/getServerVersion.rst: -------------------------------------------------------------------------------- 1 | getServerVersion 2 | ================ 3 | 4 | Returns server version number as an integer. 5 | 6 | 7 | Example 8 | ....... 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 17 13 | 14 | FetchMode('ASSOC')->PGetRow('SELECT * FROM Country WHERE Region = ? LIMIT 1', 'Caribbean'); 26 | 27 | /** 28 | * After a query made you can get the server version 29 | */ 30 | echo $db->getServerVersion(); -------------------------------------------------------------------------------- /docs/database/isConnected.rst: -------------------------------------------------------------------------------- 1 | isConnected 2 | =========== 3 | 4 | 5 | Returns boolean (true/false) depending on if it is connected or not to the 6 | database. -------------------------------------------------------------------------------- /docs/database/map.rst: -------------------------------------------------------------------------------- 1 | map 2 | === 3 | 4 | Maps the result to an object. 5 | 6 | Parameters 7 | .......... 8 | 9 | :: 10 | 11 | map($sql, $class_name=null, $params=array()) 12 | 13 | 14 | :$sql: The MySQL query to perfom on the database. 15 | :$class_name: The name of the class to instantiate, set the properties of and return. If not specified, a `stdClass `_ object is returned. 16 | :$params: An optional array of parameters to pass to the constructor for **$class_name** objects. 17 | 18 | 19 | Example 20 | ....... 21 | 22 | .. code-block:: php 23 | :linenos: 24 | :emphasize-lines: 13 25 | 26 | FetchMode('ASSOC'); 38 | $ors = $db->map('SELECT * FROM City WHERE Name="Toluca"'); 39 | 40 | echo sprintf('ID: %d CountryCode: %s', $ors->ID, $ors->CountryCode); 41 | 42 | print_r($ors); 43 | 44 | Output: 45 | 46 | .. code-block:: rest 47 | :linenos: 48 | 49 | ID: 2534 CountryCode: MEX 50 | 51 | stdClass Object 52 | ( 53 | [ID] => 2534 54 | [Name] => Toluca 55 | [CountryCode] => MEX 56 | [District] => México 57 | [Population] => 665617 58 | ) 59 | 60 | .. seealso:: 61 | 62 | `mysqli_fetch_object `_. -------------------------------------------------------------------------------- /docs/database/multipleInsert.rst: -------------------------------------------------------------------------------- 1 | multipleInsert 2 | ============== 3 | 4 | Performs one query to insert multiple records. 5 | 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | multipleInsert($table, array $col_name, array $values) 13 | 14 | 15 | :$table: Name of the table to insert the data. 16 | :$col_name: Array containing the name of the columns. 17 | :$values: Multidimensional Array containing the values. 18 | 19 | 20 | Example 21 | ....... 22 | 23 | 24 | .. code-block:: php 25 | :linenos: 26 | :emphasize-lines: 20 27 | 28 | multipleInsert('tests', array('col1', 'col2', 'col3'), $values); 48 | 49 | 50 | .. note:: 51 | 52 | The ``multipleInsert`` method uses `Prepared statements PExecute `_ to Insert the data. -------------------------------------------------------------------------------- /docs/database/qstr.rst: -------------------------------------------------------------------------------- 1 | qstr 2 | ==== 3 | 4 | Quotes a string, used when not using prepared statements and want to safetly 5 | insert/update data, it uses `real_escape_string `_. 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | qstr($string) 13 | 14 | :$string: The var to quote. 15 | 16 | 17 | Example 18 | ....... 19 | 20 | .. code-block:: php 21 | :linenos: 22 | :emphasize-lines: 13 23 | 24 | qstr($data); 37 | 38 | $db->GetRow("SELECT * FROM users WHERE name=$query"); 39 | 40 | 41 | .. warning:: 42 | 43 | This method will query the database every time is called, so in cases where 44 | you are using `cache `_ it is not very usefull, since it will need to connect 45 | to the database before doing the query. -------------------------------------------------------------------------------- /docs/database/query.rst: -------------------------------------------------------------------------------- 1 | Query 2 | ===== 3 | 4 | Fetch a result row as an associative array, a numeric array, or both. 5 | 6 | 7 | .. seealso:: 8 | 9 | `FetchMode `_ 10 | 11 | 12 | Example 13 | ....... 14 | 15 | .. code-block:: php 16 | :linenos: 17 | :emphasize-lines: 15 18 | 19 | Execute('SELECT * FROM City'); 31 | 32 | if ($rs) { 33 | while (($rows = $db->query()) != false){ 34 | list($r1,$r2,$r3) = $rows; 35 | echo "w1: $r1, w2: $r2, w3: $r3",$db->isCli(1); 36 | } 37 | } 38 | 39 | .. note:: 40 | 41 | Use `Pquery `_ when using `Prepared statements `_. -------------------------------------------------------------------------------- /docs/database/renumber.rst: -------------------------------------------------------------------------------- 1 | renumber 2 | ======== 3 | 4 | Some times you lost continuity on tables with auto increment fields, for 5 | example instead of having a sequence like : 1 2 3 4 yo have something like: 1 5 6 | 18 30; in this cases, the method ``renumber('table')`` renumbers the table. 7 | 8 | 9 | Parameters 10 | .......... 11 | 12 | :: 13 | 14 | renumber($table, $col='id') 15 | 16 | 17 | :$table: name of the table to renumber. 18 | :$col: name of the column with the **auto-increment** attribute. 19 | 20 | 21 | Example 22 | ....... 23 | 24 | 25 | .. code-block:: php 26 | :linenos: 27 | :emphasize-lines: 12 28 | 29 | renumber('table'); 41 | 42 | Example where uid is the auto-increment column: 43 | 44 | .. code-block:: php 45 | :linenos: 46 | :emphasize-lines: 12 47 | 48 | renumber('table', 'uid'); 60 | 61 | 62 | .. seealso:: 63 | 64 | MySQL `AUTO_INCREMENT `_. -------------------------------------------------------------------------------- /docs/database/useCache.rst: -------------------------------------------------------------------------------- 1 | useCache 2 | ======== 3 | 4 | Set a `DALMP\\Cache `_ instance to use. 5 | 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | useCache($cache) 13 | 14 | :$cache: A `DALMP\\Cache `_ instance. 15 | 16 | 17 | Example 18 | ....... 19 | 20 | 21 | .. code-block:: php 22 | :linenos: 23 | :emphasize-lines: 12, 14 24 | 25 | useCache($cache); 39 | 40 | $rs = $db->CacheGetOne('SELECT now()'); 41 | 42 | echo $rs, PHP_EOL; 43 | 44 | .. seealso:: 45 | 46 | `Cache method `_ -------------------------------------------------------------------------------- /docs/examples.rst: -------------------------------------------------------------------------------- 1 | Examples 2 | ======== 3 | 4 | 5 | `https://github.com/nbari/DALMP/tree/master/examples `_. 6 | -------------------------------------------------------------------------------- /docs/examples/basic.rst: -------------------------------------------------------------------------------- 1 | Basic 2 | ===== 3 | 4 | TODO 5 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | DALMP 2 | ===== 3 | 4 | **Database Abstraction Layer for MySQL using PHP** 5 | 6 | 0% fat and extremely easy to use. Only connect to database when needed. 7 | 8 | Clone the repository: 9 | 10 | .. code-block:: sh 11 | 12 | $ git clone git://github.com/nbari/DALMP.git dalmp 13 | 14 | .. seealso:: 15 | 16 | `Install `_ 17 | 18 | 19 | Details 20 | ....... 21 | 22 | * `Dependecy Injector `_ (DI) support, load once, trigger when required. 23 | * `APC `_, `Disk `_, `Memcache `_, `Redis.io `_ cache support. 24 | * Group `caching cache `_ by groups and flush by groups or individual keys. 25 | * `Prepared statements `_ ready, support dynamic building queries, auto detect types (i,d,s,b). 26 | * Secure connections with `SSL `_. 27 | * `SQLite3 Encryption `_. 28 | * Save sessions in database (mysql/sqlite) or a cache like redis/memcache/apc. 29 | * Easy to use/install/adapt. 30 | * Nested `Transactions `_ (SAVEPOINT / ROLLBACK TO SAVEPOINT). 31 | * Support connections via `unix_sockets `_. 32 | * SQL `queues `_. 33 | * Export to `CSV `_. 34 | * Trace/measure everything enabling the `debugger `_. 35 | * Works out of the box with Cloud databases like `Amazon RDS `_ or `Google cloud `_. 36 | * Lazy database connection. Connect only when needed. 37 | * `PSR-0 `_ compliance. 38 | 39 | 40 | Requirements 41 | ............ 42 | 43 | * `PHP `_ >= 5.4 44 | 45 | * A `MySQL `_ server to connect via host or `unix sockets. `_ 46 | 47 | To use the cache features you need either the redis, memcache or APC extensions 48 | compiled, otherwise disk cache will be used. 49 | 50 | * Redis extension - http://github.com/nicolasff/phpredis 51 | * Memcache PECL extencsion - http://pecl.php.net/package/memcache 52 | * APC PECL extension - http://pecl.php.net/package/APC 53 | 54 | If you want to store session encrypted then you need SQLite3 Encryption 55 | (http://sqlcipher.net). 56 | 57 | **DALMP** does not use `PDO `_, so do not worry if your PHP does not have the pdo 58 | extension. 59 | 60 | On `FreeBSD `_ you can install **DALMP** from ports: /usr/ports/databases/dalmp 61 | 62 | 63 | Table of Contents 64 | ================= 65 | 66 | .. toctree:: 67 | :maxdepth: 2 68 | 69 | about 70 | Download 71 | Install 72 | Quickstart 73 | database 74 | cache 75 | queue 76 | sessions 77 | prepared_statements 78 | DI 79 | tests 80 | examples 81 | issues 82 | navicat 83 | -------------------------------------------------------------------------------- /docs/issues.rst: -------------------------------------------------------------------------------- 1 | Issues 2 | ====== 3 | 4 | Please report any problem, bug, here: https://github.com/nbari/DALMP/issues 5 | -------------------------------------------------------------------------------- /docs/navicat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nbari/DALMP/49f74eb5b61a79d396c10ff58a9311f3e6f2f0c5/docs/navicat.jpg -------------------------------------------------------------------------------- /docs/navicat.rst: -------------------------------------------------------------------------------- 1 | Navicat 2 | ======= 3 | 4 | 5 | `Navicat Premium `_ is a multi-connections Database 6 | Administration Tool which allows you to bridge up to 6 databases within a single 7 | application: MySQL, MariaDB, SQL Server, SQLite, Oracle and PostgreSQL, create a 8 | quick and easy access to your databases all at once. `Learn more `_ 9 | 10 | Thanks 11 | ....... 12 | 13 | Many thanks `Navicat `_ for supporting Open Source projects. 14 | -------------------------------------------------------------------------------- /docs/queue.rst: -------------------------------------------------------------------------------- 1 | DALMP\\Queue 2 | ============ 3 | 4 | 5 | The ``DALMP\Queue`` class works as a dispatcher for the current Queue classes, following a common interface in order to maintain 6 | compatibility with other **DALMP** classes. 7 | 8 | *Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.* 9 | 10 | .. seealso:: 11 | 12 | `PHP Object Interfaces `_. 13 | 14 | 15 | **Parameters** 16 | 17 | :: 18 | 19 | DALMP\Queue(object) 20 | 21 | :object: An `QueueInterface instance `_. 22 | 23 | **Why?** 24 | 25 | There are times where database go down or you can't Insert/Update data into a 26 | table because of the 'too many connections mysql'. In this cases a queue always 27 | is useful so that you can later process the queries and not lose important data. 28 | 29 | **Example** 30 | 31 | .. code-block:: php 32 | :linenos: 33 | :emphasize-lines: 12, 23 34 | 35 | Execute($sql);} 56 | } catch(Exception $e) { 57 | $queue->enqueue($sql); 58 | } 59 | 60 | 61 | 62 | **See also** 63 | 64 | .. toctree:: 65 | :maxdepth: 2 66 | 67 | queue/QueueInterface 68 | queue/SQLite 69 | 70 | .. note:: 71 | 72 | The **Dalmp\\Queue** has no dependency with the `DALMP\\Database `_ class, this means that you can use only the Database or the Queue classes with out need to depend on eitherone. 73 | -------------------------------------------------------------------------------- /docs/queue/QueueInterface.rst: -------------------------------------------------------------------------------- 1 | QueueInterface 2 | ============== 3 | 4 | ``QueueInterface`` is **DALMP** interface to be use with the `DALMP\\Queue `_ class. 5 | 6 | 7 | The common methods are: 8 | 9 | =========================== ======================================= 10 | Method Description 11 | =========================== ======================================= 12 | enqueue($key) Adds an element to the queue. 13 | dequeue($limit = false) Dequeues an element from the queue. 14 | delete($key) Delete an element from the queue. 15 | X() Return the queue object. 16 | =========================== ======================================= 17 | 18 | 19 | All the queue backends must implement this `interface `_ in order to properly work with **DALMP**. 20 | 21 | __construct 22 | ........... 23 | 24 | The construct for each queue backend maybe be different and it is used for 25 | defining specific options like the host, port, path etc, 26 | 27 | .. seealso:: 28 | 29 | `PHP Object Interfaces `_. 30 | -------------------------------------------------------------------------------- /docs/queue/SQLite.rst: -------------------------------------------------------------------------------- 1 | SQLite 2 | ====== 3 | 4 | Implements the ``QueueInteface`` using as `SQLite `_ as the queue backend. 5 | 6 | Requires `PHP SQLite3 support `_ 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct($filename, $queue_name, $enc_key) 14 | 15 | :$filename: Path to the SQLite database, or :memory: to use in-memory database. 16 | :$queue_name: Name of the queue, defaults to 'default'. 17 | :$enc_key: The encryption key, default not set. 18 | 19 | 20 | .. seealso:: 21 | 22 | For using sqlite3 databases encrypted you need to install 23 | sqlcipher: `sqlcipher.net `_. 24 | 25 | 26 | Example 27 | ....... 28 | 29 | .. code-block:: php 30 | :linenos: 31 | :emphasize-lines: 5 32 | 33 | enqueue('this is a teste')), PHP_EOL; 40 | 41 | echo 'dequeue all: ', print_r($queue->dequeue(), true), PHP_EOL; 42 | 43 | echo 'dequeue only 3: ', print_r($queue->dequeue(3), true), PHP_EOL; 44 | 45 | echo 'delete from queue: ', var_dump($queue->delete(63)), PHP_EOL; 46 | 47 | 48 | .. seealso:: 49 | 50 | `Queue Examples `_. 51 | -------------------------------------------------------------------------------- /docs/sessions.rst: -------------------------------------------------------------------------------- 1 | DALMP\\Sessions 2 | =============== 3 | 4 | **DALMP** can store `PHP sessions `_ in a mysql/sqlite database or in a cache engine 5 | like redis or memcache. 6 | 7 | One of the advantage of storing the session on mysql or cache engine is the 8 | ability to make your application more scalable, without hassle. 9 | 10 | Besides the normal use of sessions, **DALMP** allows the creation of references 11 | attached to a session, this means that in some cases you can take advantage of 12 | the storage engine that keep the sessions for storing valued information. 13 | 14 | The methods you can use to handle references stored on the sessions are: 15 | 16 | ================== ========================================================== 17 | Method Description 18 | ================== ========================================================== 19 | `getSessionsRefs`_ Return array of sessions containing any reference. 20 | `getSessionRef`_ Return array of sessions containing a specific reference. 21 | `delSessionRef`_ Delete sessions containing a specific reference. 22 | ================== ========================================================== 23 | 24 | .. _getSessionsRefs: /en/latest/sessions/getSessionsRefs.html 25 | .. _getSessionRef: /en/latest/sessions/getSessionRef.html 26 | .. _delSessionRef: /en/latest/sessions/delSessionRef.html 27 | 28 | .. warning:: 29 | 30 | The `Files `_ backend, does NOT support reference handling. 31 | 32 | For example, you can store in the reference, the current user id 'UID' and 33 | configure your site to only accept users to loggin once avoiding with this 34 | duplicate entries/access using the same user/password. 35 | 36 | ``DALMP\Sessions`` implements the `SessionHandlerInterface class `_. 37 | 38 | The current available backends are: 39 | 40 | ======== ========================================================================== 41 | Backend Description 42 | ======== ========================================================================== 43 | Files Use `file system `_ to store the sessions. 44 | Memcache Use `memcache DALMP\\Cache `_. 45 | MySQL Use MySQL database `DALMP\\Database `_. 46 | Redis Use `redis DALMP\\Cache `_. 47 | SQLite Use `SQLite `_. 48 | ======== ========================================================================== 49 | 50 | 51 | **See Also:** 52 | 53 | .. toctree:: 54 | :maxdepth: 2 55 | 56 | sessions/construct 57 | sessions/Files 58 | sessions/Memcache 59 | sessions/MySQL 60 | sessions/Redis 61 | sessions/SQLite 62 | sessions/regenerate_id 63 | sessions/getSessionsRefs 64 | sessions/getSessionRef 65 | sessions/delSessionRef 66 | sessions/Example 67 | 68 | .. warning:: 69 | 70 | In order to properly use ``DALMP\Sessions`` you need (PHP 5 >= 5.4.0). 71 | -------------------------------------------------------------------------------- /docs/sessions/Example.rst: -------------------------------------------------------------------------------- 1 | Example 2 | ======= 3 | 4 | In this example the backend is going to be `redis `_ , the global reference name 5 | will be **UID**, and the hash algorithim will be **sha512**. 6 | 7 | For example, you can store in the reference **UID**, the current user id and 8 | configure your site to only accept users to loggin once, avoiding with this 9 | duplicate entries/access using the same user/password. 10 | 11 | .. code-block:: php 12 | :linenos: 13 | 14 | getSessionRef($GLOBALS['UID'])) { 34 | // user is online 35 | exit('user already logged'); 36 | } else { 37 | $sessions->regenerate_id(true); 38 | } 39 | 40 | /** 41 | * You can use $_SESSIONS like always 42 | */ 43 | $_SESSIONS['foo'] = 'bar'; 44 | -------------------------------------------------------------------------------- /docs/sessions/Files.rst: -------------------------------------------------------------------------------- 1 | Files 2 | ===== 3 | 4 | Handler for storing sessions in local hard disk, implements 5 | `SessionHandlerInterface `_. 6 | 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct($sessions_dir = false) 14 | 15 | :$sessions_dir: Path to store the sessions, default **/tmp/dalmp_sessions**. 16 | 17 | 18 | Constants 19 | ......... 20 | 21 | :: 22 | 23 | define('DALMP_SESSIONS_DIR', '/tmp/my_sessions'); 24 | 25 | 26 | If set and no ``$session_dir`` defined while initializing the class, it will 27 | use this value. 28 | 29 | .. warning:: 30 | 31 | 32 | The **Files** backend, does NOT support reference handling. 33 | -------------------------------------------------------------------------------- /docs/sessions/Memcache.rst: -------------------------------------------------------------------------------- 1 | Memcache 2 | ======== 3 | 4 | Handler for storing sessions in memcache, implements 5 | `SessionHandlerInterface `_. 6 | 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct(\DALMP\Cache\Memcache $cache, $sessions_ref = 'UID') 14 | 15 | :$cache: An instance of `DALMP\\Cache\\Memcache `_. 16 | :$sessions_ref: Name of the global reference, defaults to **UID**. 17 | 18 | 19 | Constants 20 | ......... 21 | 22 | :: 23 | 24 | define('DALMP_SESSIONS_REF', 'UID'); 25 | 26 | The global reference value that will be checked/used when handling sessions, 27 | every session will contain this value. 28 | 29 | :: 30 | 31 | define('DALMP_SESSIONS_KEY', '4d37a965ef035a7def3cd9c1baf82924c3cc792a'); 32 | 33 | A unique key that will be used to create the store the session on 34 | Memcache/Redis backends, this is useful when working in shared hosted 35 | enviroments, basically to avoid collisions. 36 | -------------------------------------------------------------------------------- /docs/sessions/MySQL.rst: -------------------------------------------------------------------------------- 1 | MySQL 2 | ===== 3 | 4 | Handler for storing sessions in MySQL, implements 5 | `SessionHandlerInterface `_. 6 | 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct(\DALMP\Database $DB, $sessions_ref = 'UID') 14 | 15 | :$DB: An instance of `DALMP\\Database `_. 16 | :$sessions_ref: Name of the global reference, defaults to **UID**. 17 | 18 | 19 | Constants 20 | ......... 21 | 22 | :: 23 | 24 | define('DALMP_SESSIONS_REF', 'UID'); 25 | 26 | The global reference value that will be checked/used when handling sessions, 27 | every session will contain this value. 28 | 29 | :: 30 | 31 | define('DALMP_SESSIONS_TABLE', 'dalmp_sessions'); 32 | 33 | Name of the MySQL table where sessions will be stored, by default the table 34 | 'dalmp_sessions' will be used. 35 | 36 | 37 | MySQL table schema 38 | .................. 39 | 40 | For storing PHP sessions on mysql you need to create a table with the following 41 | schema: 42 | 43 | .. code-block:: sql 44 | :linenos: 45 | 46 | CREATE TABLE IF NOT EXISTS `dalmp_sessions` ( 47 | `sid` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', 48 | `expiry` int(11) unsigned NOT NULL DEFAULT '0', 49 | `data` longtext CHARACTER SET utf8 COLLATE utf8_bin, 50 | `ref` varchar(255) DEFAULT NULL, 51 | `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 52 | PRIMARY KEY (`sid`), 53 | KEY `index` (`ref`,`sid`,`expiry`) 54 | ) DEFAULT CHARSET=utf8; 55 | 56 | 57 | .. seealso:: 58 | 59 | `DALMP Quickstart `_. 60 | -------------------------------------------------------------------------------- /docs/sessions/Redis.rst: -------------------------------------------------------------------------------- 1 | Redis 2 | ===== 3 | 4 | Handler for storing sessions in redis, implements 5 | `SessionHandlerInterface `_. 6 | 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct(\DALMP\Cache\Redis $cache, $sessions_ref = 'UID') 14 | 15 | :$cache: An instance of `DALMP\\Cache\\Redis `_. 16 | :$sessions_ref: Name of the global reference, defaults to **UID**. 17 | 18 | 19 | Constants 20 | ......... 21 | 22 | :: 23 | 24 | define('DALMP_SESSIONS_REF', 'UID'); 25 | 26 | The global reference value that will be checked/used when handling sessions, 27 | every session will contain this value. 28 | 29 | :: 30 | 31 | define('DALMP_SESSIONS_KEY', '4d37a965ef035a7def3cd9c1baf82924c3cc792a'); 32 | 33 | A unique key that will be used to create the store the session on 34 | Memcache/Redis backends, this is useful when working in shared hosted 35 | enviroments, basically to avoid collisions. 36 | -------------------------------------------------------------------------------- /docs/sessions/SQLite.rst: -------------------------------------------------------------------------------- 1 | SQLite 2 | ====== 3 | 4 | Handler for storing sessions in SQLite, implements 5 | `SessionHandlerInterface `_. 6 | 7 | 8 | __construct 9 | ........... 10 | 11 | :: 12 | 13 | __construct($filename = false, $sessions_ref = 'UID', $enc_key = false) 14 | 15 | :$filename: Path to the SQLite database, or :memory: to use in-memory database. 16 | :$sessions_ref: Name of the global reference, defaults to **UID**. 17 | :$enc_key: The encryption key, default not set. 18 | 19 | .. seealso:: 20 | 21 | For using sqlite3 databases encrypted you need to install 22 | sqlcipher: `sqlcipher.net `_. 23 | -------------------------------------------------------------------------------- /docs/sessions/construct.rst: -------------------------------------------------------------------------------- 1 | __construct 2 | =========== 3 | 4 | In order to use the ``DALMP\Sessions`` you need to create an instance of it, 5 | while creating the instance you define the backend that will store the sessions 6 | and the hash algorithm used to create them. 7 | 8 | Parameters 9 | .......... 10 | 11 | :: 12 | 13 | __construct($handler = false, $algo = 'sha256') 14 | 15 | :$handler: If false uses `SQLite `_, otherwise argument must be an instance of `SessionHandlerInterface `_. 16 | :$algo: Allows you to specify the `hash algorithm `_ used to generate the session IDs - default **sha256**. 17 | 18 | The current backends are: 19 | 20 | * `Files `_ (does NOT support reference handling). 21 | * `Memcache `_. 22 | * `MySQL `_. 23 | * `Redis `_. 24 | * `SQLite `_. 25 | 26 | 27 | .. note:: 28 | 29 | The construct for each cache backend maybe be different and it is used for 30 | defining specific options like the host, port, path, etc. 31 | 32 | 33 | Constants 34 | ......... 35 | 36 | :: 37 | 38 | define('DALMP_SESSIONS_MAXLIFETIME', 900); 39 | 40 | If set, the value is used as an argument for the `session.gc_maxlifetime `_ with specifies the number of seconds after which data will be seen as 41 | 'garbage' and potentially cleaned up. 42 | 43 | :: 44 | 45 | define('DALMP_SESSIONS_REF', 'UID'); 46 | 47 | The global reference value that will be checked/used when handling sessions, 48 | every session will contain this value. 49 | 50 | :: 51 | 52 | define('DALMP_SESSIONS_KEY', '4d37a965ef035a7def3cd9c1baf82924c3cc792a'); 53 | 54 | A unique key that will be used to create the store the session on 55 | Memcache/Redis backends, this is useful when working in shared hosted 56 | enviroments, basically to avoid collisions. 57 | -------------------------------------------------------------------------------- /docs/sessions/delSessionRef.rst: -------------------------------------------------------------------------------- 1 | delSessionRef 2 | ============= 3 | 4 | Delete sessions containing a specific reference. 5 | 6 | Parameters 7 | .......... 8 | 9 | delSessionRef($ref) 10 | 11 | :$ref: Value of the reference to search for. 12 | 13 | 14 | Example 15 | ....... 16 | 17 | In this example all the sessions containing the value '3', will be deleted. 18 | 19 | .. code-block:: php 20 | :linenos: 21 | :emphasize-lines: 11 22 | 23 | delSessionRef('3'); 34 | -------------------------------------------------------------------------------- /docs/sessions/getSessionRef.rst: -------------------------------------------------------------------------------- 1 | getSessionRef 2 | ============= 3 | 4 | Return array of session containing a specific reference. 5 | 6 | Parameters 7 | .......... 8 | 9 | getSessionRef($ref) 10 | 11 | :$ref: Value of the reference to search for. 12 | 13 | 14 | Example 15 | ....... 16 | 17 | In this example all the sessions containing the value '3', will returned. 18 | 19 | .. code-block:: php 20 | :linenos: 21 | :emphasize-lines: 11 22 | 23 | getSessionRef('3'); 34 | -------------------------------------------------------------------------------- /docs/sessions/getSessionsRefs.rst: -------------------------------------------------------------------------------- 1 | getSessionsRefs 2 | =============== 3 | 4 | Return array of sessions containing any reference. 5 | 6 | Example 7 | ....... 8 | 9 | 10 | .. code-block:: php 11 | :linenos: 12 | :emphasize-lines: 11 13 | 14 | getSessionsRefs(); 25 | -------------------------------------------------------------------------------- /docs/sessions/regenerate_id.rst: -------------------------------------------------------------------------------- 1 | regenerate_id 2 | ============= 3 | 4 | The ``regenerate_id`` method, regenerate a sessions and create a fingerprint, 5 | helps to prevent HTTP session hijacking attacks. 6 | 7 | Parameters 8 | .......... 9 | 10 | :: 11 | 12 | regenerate_id($use_IP = true) 13 | 14 | :$use_IP: Include client IP address on the fingerprint. 15 | 16 | 17 | Example 18 | ....... 19 | 20 | 21 | .. code-block:: php 22 | :linenos: 23 | :emphasize-lines: 8 24 | 25 | regenerate_id(true); 33 | } 34 | 35 | $_SESSION['test'] = 1 + @$_SESSION['test']; 36 | 37 | echo $_SESSION['test']; 38 | 39 | echo session_id(); 40 | 41 | .. seealso:: 42 | 43 | `PHP session_regenerate_id `_. 44 | -------------------------------------------------------------------------------- /docs/tests.rst: -------------------------------------------------------------------------------- 1 | Tests 2 | ===== 3 | 4 | For testing **DALMP** load the `world.sql.gz `_ located at the examples dir: 5 | 6 | .. code-block:: shell 7 | :linenos: 8 | 9 | gzcat examples/world.sql.gz | mysql -uroot dalmp 10 | 11 | 12 | *You can try also with gzip, gunzip, zcat as alternative to gzcat* 13 | 14 | That will load all the `world tables `_ into the dalmp database and also create the 15 | dalmp_sessions table. 16 | 17 | For testing purposes the same DSN (same database) is used when testing sessions 18 | and database, in practice you can have different DSN depending on your 19 | requirements. 20 | 21 | You can however configure your DNS:: 22 | 23 | cp phpunit.xml.dist phpunit.xml 24 | 25 | Edit the DSN section:: 26 | 27 | ... 28 | 29 | 30 | 31 | ... 32 | 33 | Install `composer `_ and required packages:: 34 | 35 | curl -sS https://getcomposer.org/installer | php -- --install-dir=bin 36 | 37 | Install `phpunit `_ via composer:: 38 | 39 | ./bin/composer.phar install --dev 40 | 41 | For example to test only the `Cache\\Memcache `_:: 42 | 43 | ./bin/phpunit --testsuite CacheMemcache --tap -c phpunit.xml 44 | 45 | To run all the tests: 46 | 47 | .. code-block:: shell 48 | 49 | ./bin/phpunit --tap -c phpunit.xml 50 | -------------------------------------------------------------------------------- /examples/README.markdown: -------------------------------------------------------------------------------- 1 | DALMP - examples 2 | ================ 3 | 4 | It is recommended to run the examples in CLI mode, the only exception is when 5 | testing sessions. 6 | 7 | All examples use as user and password the environment variables: 8 | 9 | * MYSQL_USER 10 | * MYSQL_PASS 11 | * MYSQL_HOST 12 | * MYSQL_PORT 13 | 14 | For example if using shell csh you can use something like: 15 | 16 | setenv MYSQL_USER dbadmin 17 | setenv MYSQL_PASS secret 18 | setenv MYSQL_HOST 192.168.1.30 19 | 20 | 21 | while testing, on a terminal you may using something like this: 22 | 23 | mysqladmin -r -i 1 processlist -uroot -p -------------------------------------------------------------------------------- /examples/all_together/database-cache-sessions.php: -------------------------------------------------------------------------------- 1 | database($DSN); 16 | 17 | $redis_cache = $di->cache_redis('127.0.0.1', 6379); 18 | 19 | $cache = $di->cache($redis_cache); 20 | 21 | $sessions = $di->sessions($di->sessions_redis($redis_cache), 'sha512'); 22 | $sessions->regenerate_id(true); 23 | 24 | $db->useCache($cache); 25 | 26 | $now = $db->CachegetOne('SELECT NOW()'); 27 | 28 | echo $now, PHP_EOL; 29 | 30 | echo session_id(); 31 | -------------------------------------------------------------------------------- /examples/all_together/di.php: -------------------------------------------------------------------------------- 1 | database("utf8://$user:$password@$host:$port/dalmp"); 13 | echo $ok; 14 | $ok->debug(); 15 | 16 | $now = $ok->getOne('SELECT NOW()'); 17 | echo $now,PHP_EOL; 18 | sleep(10); 19 | $now = $ok->getOne('SELECT NOW()'); 20 | echo $now,PHP_EOL; 21 | sleep(10); 22 | $city = $ok->PgetAll('SELECT * FROM City WHERE name like ?', '%timor%'); 23 | print_r($city); 24 | sleep(10); 25 | $now = $ok->getOne('SELECT NOW()'); 26 | echo $now,PHP_EOL; 27 | 28 | echo 'ping: '; 29 | var_dump($ok->X()->ping()); 30 | 31 | sleep(5); 32 | 33 | class teste 34 | { 35 | public function __construct() 36 | { 37 | print_r(func_get_args()); 38 | } 39 | 40 | public function foo() 41 | { 42 | echo __CLASS__ . __METHOD__; 43 | } 44 | 45 | } 46 | 47 | $di->addObject('teste', new teste()); 48 | 49 | $a = $di->teste(); 50 | 51 | $a->foo(); 52 | 53 | $di->addObject('test2', $di->share(function () { 54 | return new teste(); 55 | })); 56 | 57 | echo PHP_EOL; 58 | $b = $di->test2(); 59 | $b->foo(); 60 | 61 | echo PHP_EOL; 62 | $c = $di->test2(); 63 | $c->foo(); 64 | 65 | echo PHP_EOL; 66 | 67 | $d = $di->test2(); 68 | $d->foo(); 69 | -------------------------------------------------------------------------------- /examples/cache/cache-group-DSN.php: -------------------------------------------------------------------------------- 1 | FetchMode('ASSOC'); 18 | 19 | /** 20 | * Cache for 5 minutes, group A 21 | */ 22 | $rs = $db->CachePGetAll(300,'SELECT * FROM Country WHERE Region = ?', 'Caribbean', 'group:A'); 23 | echo count($rs), PHP_EOL; 24 | $timer->setMark('300'); 25 | 26 | /** 27 | * Cache for 1 day (86400 seconds), group B 28 | */ 29 | $rs = $db->CachePGetAll(86400, 'SELECT * FROM Country WHERE Continent = ?', 'Europe', 'group:B'); 30 | echo count($rs), PHP_EOL; 31 | $timer->setMark('86400'); 32 | 33 | /** 34 | * Cache for 1 hour (default), group C 35 | */ 36 | $rs = $db->CachePGetAll('SELECT * FROM Country WHERE Population <= ?', 100000, 'group:C'); 37 | echo count($rs), PHP_EOL; 38 | $timer->setMark('default'); 39 | 40 | /** 41 | * lazy connection test query DB only when needed 42 | */ 43 | $db->debug(); 44 | $db->closeConnection(); 45 | 46 | /** 47 | * Cache for 5 minutes, group A 48 | */ 49 | $rs = $db->CachePGetAll('SELECT * FROM Country WHERE Region = ?', 'Caribbean'); 50 | echo count($rs), PHP_EOL; 51 | $timer->setMark('lazy'); 52 | 53 | /** 54 | * flush only group A 55 | */ 56 | $db->CacheFlush('group:A'); 57 | 58 | /** 59 | * Cache for 5 minutes, group A 60 | */ 61 | $rs = $db->CachePGetAll(300,'SELECT * FROM Country WHERE Region = ?', 'Caribbean', 'group:A'); 62 | echo count($rs), PHP_EOL; 63 | $timer->setMark('connect'); 64 | 65 | # ------------------------------------------------------------------------------ 66 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 67 | $timer->printMarks(); 68 | echo str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 69 | -------------------------------------------------------------------------------- /examples/cache/cache-group.php: -------------------------------------------------------------------------------- 1 | useCache(new DALMP\Cache(new DALMP\Cache\Redis('127.0.0.1', 6379))); 18 | 19 | $db->FetchMode('ASSOC'); 20 | 21 | /** 22 | * Cache for 5 minutes, group A 23 | */ 24 | $rs = $db->CachePGetAll(300,'SELECT * FROM Country WHERE Region = ?', 'Caribbean', 'group:A'); 25 | echo count($rs), PHP_EOL; 26 | $timer->setMark('300'); 27 | 28 | /** 29 | * Cache for 1 day (86400 seconds), group B 30 | */ 31 | $rs = $db->CachePGetAll(86400, 'SELECT * FROM Country WHERE Continent = ?', 'Europe', 'group:B'); 32 | echo count($rs), PHP_EOL; 33 | $timer->setMark('86400'); 34 | 35 | /** 36 | * Cache for 1 hour (default), group C 37 | */ 38 | $rs = $db->CachePGetAll('SELECT * FROM Country WHERE Population <= ?', 100000, 'group:C'); 39 | echo count($rs), PHP_EOL; 40 | $timer->setMark('default'); 41 | 42 | /** 43 | * lazy connection test query DB only when needed 44 | */ 45 | $db->debug(); 46 | $db->closeConnection(); 47 | 48 | /** 49 | * Cache for 5 minutes, group A 50 | */ 51 | $rs = $db->CachePGetAll('SELECT * FROM Country WHERE Region = ?', 'Caribbean'); 52 | echo count($rs), PHP_EOL; 53 | $timer->setMark('lazy'); 54 | 55 | /** 56 | * flush only group A 57 | */ 58 | $db->CacheFlush('group:A'); 59 | 60 | /** 61 | * Cache for 5 minutes, group A 62 | */ 63 | $rs = $db->CachePGetAll(300,'SELECT * FROM Country WHERE Region = ?', 'Caribbean', 'group:A'); 64 | echo count($rs), PHP_EOL; 65 | $timer->setMark('connect'); 66 | 67 | # ------------------------------------------------------------------------------ 68 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 69 | $timer->printMarks(); 70 | echo str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 71 | -------------------------------------------------------------------------------- /examples/cache/cache.php: -------------------------------------------------------------------------------- 1 | useCache($memcache); 38 | $rs = $db->CacheGetAll(300, $sql, 'mykey'); 39 | $timer->setMark('memcache'); 40 | echo count($rs),PHP_EOL; 41 | $rs = $db->CacheGetAll(300, $sql, 'mykey'); 42 | $timer->setMark('memcache2'); 43 | echo count($rs),PHP_EOL; 44 | 45 | /** 46 | * Cache for 5 minutes with key: mykey using redis cache 47 | */ 48 | $db->debug(); 49 | $db->useCache($redis); 50 | $rs = $db->CacheGetAll(300, $sql, 'mykey'); 51 | $timer->setMark('redis'); 52 | echo count($rs),PHP_EOL; 53 | $rs = $db->CacheGetAll(300, $sql, 'mykey'); 54 | $db->debug('off'); 55 | $timer->setMark('redis2'); 56 | echo count($rs),PHP_EOL; 57 | 58 | /** 59 | * Cache for 5 minutes with key: mykey using disk cache 60 | */ 61 | $db->useCache($disk); 62 | $rs = $db->CacheGetAll(300, $sql, 'mykey'); 63 | $timer->setMark('disk'); 64 | echo count($rs),PHP_EOL; 65 | $rs = $db->CacheGetAll(300, $sql, 'mykey'); 66 | $timer->setMark('disk2'); 67 | echo count($rs),PHP_EOL; 68 | 69 | /** 70 | * flush the query $sql with key on DISK cache instance 71 | */ 72 | $db->CacheFlush($sql, 'mykey'); 73 | 74 | /** 75 | * flush the query $sql with key only on Redis cache instance 76 | */ 77 | $db->useCache($redis); 78 | $db->CacheFlush($sql, 'mykey'); 79 | 80 | /** 81 | * flush all the cache in all instances 82 | */ 83 | foreach (array('memcache', 'redis', 'disk') as $val) { 84 | $db->useCache(${$val}); 85 | $db->CacheFlush($sql, 'mykey'); 86 | } 87 | 88 | # ------------------------------------------------------------------------------ 89 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 90 | $timer->printMarks(); 91 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 92 | -------------------------------------------------------------------------------- /examples/cache/cache_disk.php: -------------------------------------------------------------------------------- 1 | set('mykey', 'xpto', 300); 14 | var_dump($cache->get('mykey')); 15 | 16 | print_r($cache->stats()); 17 | #------------------------------------------------------------------------------ 18 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 19 | -------------------------------------------------------------------------------- /examples/cache/cache_memcache.php: -------------------------------------------------------------------------------- 1 | set('mykey', 'xpto', 300); 14 | var_dump($cache->get('mykey')); 15 | 16 | $cache->X()->replace('mykey', 'otpx', false, 300); 17 | var_dump($cache->get('mykey')); 18 | 19 | #------------------------------------------------------------------------------ 20 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 21 | -------------------------------------------------------------------------------- /examples/cache/cache_redis.php: -------------------------------------------------------------------------------- 1 | set('mykey', 'xpto', 300); 14 | var_dump($cache->get('mykey')); 15 | 16 | $cache->X()->HSET('myhash', 'field1', 'hello'); 17 | var_dump($cache->X()->HGET('myhash', 'field1')); 18 | var_dump($cache->X()->HGETALL('myhash')); 19 | 20 | #------------------------------------------------------------------------------ 21 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 22 | -------------------------------------------------------------------------------- /examples/cache/cache_redis2.php: -------------------------------------------------------------------------------- 1 | set('mykey', 'xpto', 300); 14 | var_dump($cache->get('mykey')); 15 | 16 | $cache->X()->HSET('myhash', 'field1', 'hello'); 17 | var_dump($cache->X()->HGET('myhash', 'field1')); 18 | var_dump($cache->X()->HGETALL('myhash')); 19 | 20 | #------------------------------------------------------------------------------ 21 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 22 | -------------------------------------------------------------------------------- /examples/database/2databases.php: -------------------------------------------------------------------------------- 1 | FetchMode('ASSOC')->getall('SELECT * FROM Country limit 1'); 11 | print_r($rs1); 12 | 13 | $rs2 = $db2->FetchMode('NUM')->getall('SELECT * FROM City limit 1'); 14 | print_r($rs2); 15 | 16 | # ------------------------------------------------------------------------------ 17 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 18 | -------------------------------------------------------------------------------- /examples/database/X.php: -------------------------------------------------------------------------------- 1 | database("utf8://$user:$password@$host:$port/dalmp"); 14 | $db->debug(); 15 | 16 | echo 'connect ', var_dump($db->connect()); 17 | sleep(3); 18 | echo 'ping: ', var_dump($db->X()->ping()); 19 | echo 'thread_safe: ', var_dump($db->X()->thread_safe()); 20 | echo 'client_info: ', var_dump($db->X()->get_client_info()); 21 | echo 'client_version: ', var_dump($db->X()->client_version); 22 | echo 'server_info: ', var_dump($db->X()->server_info); 23 | echo 'server_version: ', var_dump($db->X()->server_version); 24 | 25 | echo $timer->isCli(1), $db, $timer->isCli(1); 26 | 27 | echo $timer->isCli(1), $db->GetOne('SELECT NOW()'), $timer->isCli(1); 28 | 29 | $db->closeConnection(); 30 | 31 | echo 'is connected: ', var_dump($db->isConnected()); 32 | sleep(3); 33 | 34 | echo 'ping: ', var_dump($db->X()->ping()); 35 | echo $timer->isCli(1), $db->GetOne('SELECT NOW()'), $timer->isCli(1); 36 | sleep(3); 37 | 38 | # ------------------------------------------------------------------------------ 39 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 40 | -------------------------------------------------------------------------------- /examples/database/cleanDB.php: -------------------------------------------------------------------------------- 1 | GetCol('SHOW TABLES') as $table) { 15 | $rs = $db->Execute("OPTIMIZE TABLE $table"); 16 | echo "optimizing $table: $rs",PHP_EOL; 17 | $rs = $db->Execute("REPAIR TABLE $table QUICK"); 18 | echo "repairing $table: $rs",PHP_EOL; 19 | } 20 | 21 | # ------------------------------------------------------------------------------ 22 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 23 | -------------------------------------------------------------------------------- /examples/database/cluster.php: -------------------------------------------------------------------------------- 1 | FetchMode('ASSOC')->PgetAll('SELECT NOW()'); 25 | } catch (\Exception $e) { 26 | array_shift($dsns); 27 | $cdb = new DALMP\Database($dsns[0]); 28 | if ($dsns) { 29 | $cdb = new DALMP\Database($dsns[0]); 30 | } else { 31 | throw $e; 32 | } 33 | echo $e->getMessage(), PHP_EOL; 34 | } 35 | } 36 | print_r($result); 37 | 38 | #------------------------------------------------------------------------------ 39 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 40 | -------------------------------------------------------------------------------- /examples/database/csv.php: -------------------------------------------------------------------------------- 1 | csv("SELECT * FROM Country WHERE Continent = 'Europe'"); 20 | 21 | // prepared statements 22 | $db->csv('SELECT * FROM Country WHERE Continent = ?', 'Europe'); 23 | 24 | # ------------------------------------------------------------------------------ 25 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 26 | -------------------------------------------------------------------------------- /examples/database/iterator.php: -------------------------------------------------------------------------------- 1 | FetchMode('ASSOC')->PGetAll('SELECT @i:=@i+1 AS iterator, t.* from Country as t, (SELECT @i:=0) AS r'); 15 | 16 | print_r($rs); 17 | 18 | # ------------------------------------------------------------------------------ 19 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 20 | echo str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 21 | -------------------------------------------------------------------------------- /examples/database/locale.php: -------------------------------------------------------------------------------- 1 | GetOne('SELECT NOW()'); 17 | 18 | /** 19 | * load zone files to mysql 20 | * mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql 21 | */ 22 | $db->PExecute('SET time_zone=?','+00:00'); 23 | 24 | echo PHP_EOL, 'UTC time: ', $db->GetOne('SELECT NOW()'); 25 | echo PHP_EOL, 'lc_time_names: ', $db->GetOne('SELECT @@lc_time_names'); 26 | echo ': ', $db->PGetOne("SELECT DATE_FORMAT(?,'%W %a %M %b')", '2010-01-01'); 27 | 28 | $db->PExecute('SET lc_time_names=?', 'es_MX'); 29 | 30 | echo PHP_EOL, 'lc_time_names: ', $db->GetOne('SELECT @@lc_time_names'); 31 | echo ': ', $db->PGetOne("SELECT DATE_FORMAT(?,'%W %a %M %b')", '2010-01-01'); 32 | 33 | $db->PExecute('SET lc_time_names=?', 'pt_BR'); 34 | echo PHP_EOL, 'lc_time_names: ', $db->GetOne('SELECT @@lc_time_names'); 35 | echo ': ', $db->PGetOne("SELECT DATE_FORMAT(?,'%W %a %M %b')", '2010-01-01'); 36 | 37 | # ------------------------------------------------------------------------------ 38 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 39 | -------------------------------------------------------------------------------- /examples/database/map.php: -------------------------------------------------------------------------------- 1 | FetchMode('ASSOC'); 15 | $ors = $db->map('SELECT * FROM City WHERE Name="Toluca"'); 16 | 17 | echo sprintf('ID: %d CountryCode: %s', $ors->ID, $ors->CountryCode), PHP_EOL; 18 | 19 | print_r($ors); 20 | 21 | # ------------------------------------------------------------------------------ 22 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 23 | echo str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 24 | -------------------------------------------------------------------------------- /examples/database/multipleinsert.php: -------------------------------------------------------------------------------- 1 | debug(); 14 | 15 | $values = array( 16 | array(1,2,3), 17 | array(1,3), 18 | array('date','select', 3), 19 | array('niño','coraçao', 'Ú'), 20 | array(null,5,7) 21 | ); 22 | 23 | $rs = $db->multipleInsert('tests', array('col1', 'col2', 'col3'), $values); 24 | 25 | var_dump($rs); 26 | 27 | print_r($db->FetchMode('ASSOC')->GetALL('SELECT * FROM tests')); 28 | 29 | # ------------------------------------------------------------------------------ 30 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 31 | -------------------------------------------------------------------------------- /examples/database/preparedStatements.php: -------------------------------------------------------------------------------- 1 | PExecute('SET time_zone=?','+00:00'); 19 | 20 | $db->FetchMode('ASSOC'); 21 | 22 | $sql = 'SELECT Name, Continent FROM Country WHERE Population > ? AND Code LIKE ? LIMIT ?'; 23 | $rs = $db->PGetAll($sql, 10000000, '%P%', 2); 24 | 25 | print_r($rs); 26 | 27 | $rs = $db->Execute('DROP TABLE IF EXISTS `tests`'); 28 | $rs = $db->Execute('CREATE TABLE `tests` (id INT(11) unsigned NOT NULL AUTO_INCREMENT, col1 varchar(255), col2 varchar(255), col3 varchar(255), status iNT(1), PRIMARY KEY (id))'); 29 | $rs = $db->AutoExecute('tests', array('col1' => 'ai eu', 'col2' => 2, 'status' => 0)); 30 | 31 | /** 32 | * status value is 0 or 1 on table 33 | * NOTICE the use of === 34 | */ 35 | $sql = 'SELECT status FROM tests WHERE id=?'; 36 | $rs = $db->PgetOne($sql, 3); 37 | if ($rs === false) { 38 | echo "no result".$timer->isCli(1); 39 | } elseif ($rs == 0) { 40 | echo "$rs = 0".$timer->isCli(1); 41 | } else { 42 | echo "$rs > 0".$timer->isCli(1); 43 | } 44 | 45 | /** 46 | * passing an array as an argument 47 | * helpful in cases where searching float values stored on varchar fields 48 | * $db->PGetAll($sql, array('s' => 99.3, 1)); 49 | */ 50 | $sql = 'SELECT * FROM tests WHERE id=? AND col1=?'; 51 | $rs = $db->PGetAll($sql, array(3, 's' => 'string')); 52 | var_dump($rs); 53 | 54 | /** 55 | * using the Prepare method, 56 | * Useful when building dynamic queries that require prepared statements 57 | * The prepare method automatically detect the input type, 58 | * you can also override this, using something like: Prepare('s','1e1'); 59 | * if no input it will return the array with the prepared statements 60 | */ 61 | $X = 3; 62 | $id = 1; 63 | $db->Prepare($id); 64 | $sql = 'SELECT * FROM tests WHERE id=? '; 65 | if ($X == 3) { 66 | $db->Prepare($X); 67 | $sql .= 'AND id !=? '; 68 | } 69 | $db->Prepare('s', 'ai eu'); 70 | $sql .= 'AND col1=?'; 71 | 72 | /** 73 | * this will produce a query like: 74 | * "sql: SELECT * FROM tests WHERE id=? AND id !=? AND col1=?" with params = ["iis",1,3,"ai eu"] 75 | */ 76 | 77 | echo "sql: $sql" , PHP_EOL; 78 | echo 'Args: ', PHP_EOL; 79 | print_r($db->Prepare()); 80 | 81 | $rs = $db->PgetAll($sql, $db->Prepare()); 82 | echo 'Result: ', print_r($rs), PHP_EOL; 83 | 84 | /** 85 | * insert and get last_insert_id 86 | */ 87 | $db->PExecute('INSERT INTO tests (col1, col2) VALUES(?,?)', rand(), rand()); 88 | echo 'Last insert ID: ', $db->Insert_Id(); 89 | 90 | # ------------------------------------------------------------------------------ 91 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 92 | -------------------------------------------------------------------------------- /examples/database/query_Execute.php: -------------------------------------------------------------------------------- 1 | setMark('start'); 8 | 9 | $user = getenv('MYSQL_USER') ?: 'root'; 10 | $password = getenv('MYSQL_PASS') ?: ''; 11 | $host = getenv('MYSQL_HOST') ?: '127.0.0.1'; 12 | $port = getenv('MYSQL_PORT') ?: '3306'; 13 | 14 | $db = new DALMP\Database("utf8://$user:$password@$host:$port/dalmp"); 15 | 16 | $db->FetchMode('NUM'); 17 | 18 | $sql = 'SELECT * FROM City'; 19 | $rs = $db->Execute($sql); 20 | 21 | if ($rs) { 22 | while (($rows = $db->query()) != false) { 23 | list($r1,$r2,$r3) = $rows; 24 | echo "w1: $r1, w2: $r2, w3: $r3", $timer->isCli(1); 25 | } 26 | } 27 | 28 | $timer->setMark('while'); 29 | 30 | /** 31 | * doing the same but consuming more memory. 32 | * Below the returned $rs2 array is not referential. Because of that, the system 33 | * will use excesive memory. With large columns. 34 | */ 35 | $rs2 = $db->GetAll($sql); 36 | foreach ($rs2 as $value) { 37 | list($r1,$r2,$r3) = $value; 38 | echo "f1: $r1, f2: $r2, f3: $r3", $timer->isCli(1); 39 | } 40 | 41 | $timer->setMark('foreach'); 42 | 43 | /** 44 | * prepared statements 45 | * and array needs to be passed as an argument 46 | */ 47 | $rs = $db->PExecute('SELECT * FROM Country WHERE Continent = ?', 'Europe'); 48 | $out = array(); 49 | while ($rows = $db->Pquery($out)) { 50 | print_r($out); 51 | } 52 | 53 | $rs = $db->PExecute('UPDATE Country SET code=? WHERE Code="PRT"', 'PRT'); 54 | 55 | /** 56 | * Returns the number of rows affected by INSERT, UPDATE, or DELETE query. 57 | * an UPDATE prepared statement which contains the same data as that already 58 | * in the database returns 0 for affected_rows 59 | */ 60 | echo $db->getNumOfRowsAffected(), PHP_EOL; 61 | 62 | $timer->setMark('stmt'); 63 | 64 | echo $timer->isCli(1); 65 | 66 | # ------------------------------------------------------------------------------ 67 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 68 | $timer->printMarks(); 69 | echo str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 70 | -------------------------------------------------------------------------------- /examples/database/queue.php: -------------------------------------------------------------------------------- 1 | Execute($sql); 28 | } catch (\Exception $e) { 29 | $db->queue($sql, 'my-queue'); 30 | } 31 | 32 | /** 33 | * Save some $_POST/$_GET data in json format 34 | */ 35 | $get = array('uuid' => $db->UUID(), 'cdate' => @date('c'), 'field1' => 1, 'field2' => 2); 36 | $db->queue(json_encode($get), 'json'); 37 | 38 | /** 39 | * this can be called on a cron or manually 40 | */ 41 | foreach ($db->readQueue() as $key => $value) { 42 | $queue = $value['queue']; 43 | $data = base64_decode($value['data']); 44 | $cdate = $value['cdate']; 45 | echo "$queue - $data - $cdate".$timer->isCli(1); 46 | /** 47 | * try to re-execute the query 48 | */ 49 | # $rs = $db->Execute($data); 50 | } 51 | 52 | /** 53 | * helpful on CLI 54 | */ 55 | echo $timer->isCli(1); 56 | // read all queues 57 | $db->readQueue('*', 1); 58 | echo $timer->isCli(1); 59 | // read only json queue 60 | $db->readQueue('json', 1); 61 | 62 | # ----------------------------------------------------------------------------------------------------------------- 63 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 64 | -------------------------------------------------------------------------------- /examples/database/redis.php: -------------------------------------------------------------------------------- 1 | FetchMode('ASSOC'); 17 | $rs = $db->CacheGetAll('SELECT * FROM City'); 18 | 19 | print_r($rs); 20 | 21 | # ------------------------------------------------------------------------------ 22 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL; 23 | echo str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 24 | -------------------------------------------------------------------------------- /examples/database/select_db.php: -------------------------------------------------------------------------------- 1 | GetOne('SELECT DATABASE()'); 18 | echo $rs, PHP_EOL; 19 | 20 | $db->X()->select_db('mysql'); 21 | 22 | $rs = $db->GetOne('SELECT DATABASE()'); 23 | echo $rs, PHP_EOL; 24 | 25 | #------------------------------------------------------------------------------ 26 | echo PHP_EOL, str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 27 | -------------------------------------------------------------------------------- /examples/database/start.php: -------------------------------------------------------------------------------- 1 | getOne('SELECT now()'); 48 | } catch (\Exception $e) { 49 | print_r($e->getMessage()); 50 | } 51 | 52 | /** 53 | * 1 log to single file 54 | * 2 log to multiple files (creates a log per request) 55 | * 'off' to stop debuging 56 | */ 57 | $db->debug(1); 58 | 59 | echo $db, PHP_EOL; // print connection details 60 | 61 | /** 62 | * example of a connection using UTF8 charset 63 | * 64 | * charset: utf8 65 | * user: dalmp 66 | * password: password 67 | * host: 127.0.0.1 68 | * port: 3306 69 | * database: dalmptest 70 | */ 71 | $db = new DALMP\Database('utf8://dalmp:password@127.0.0.1:3306/dalmptest'); 72 | try { 73 | $db->getOne('SELECT now()'); 74 | } catch (\Exception $e) { 75 | print_r($e->getMessage()); 76 | } 77 | 78 | echo PHP_EOL, $db, PHP_EOL; // will print: DALMP :: connected to: db2, Character set: utf8, 127.0.0.1 via TCP/IP, Server version: ... 79 | 80 | /** 81 | * example using SSL (OpenSSL support must be enabled for this to work) 82 | * 83 | * charset: latin1 84 | * user: root 85 | * password: mysql 86 | * host: 127.0.0.1 87 | * database: dalmp 88 | * 89 | * An array containing the SSL parameters must be passed as the second argument to the database method: 90 | * 91 | * $db = new DALMP(DSN, $ssl_array); 92 | * 93 | * key = The path name to the key file. 94 | * cert = The path name to the certificate file. 95 | * ca = The path name to the certificate authority file. 96 | * capath = The pathname to a directory that contains trusted SSL CA certificates in PEM format. 97 | * cipher = A list of allowable ciphers to use for SSL encryption. 98 | * 99 | */ 100 | $ssl = array('key' => null, 'cert' => null, 'ca' => 'mysql-ssl.ca-cert.pem', 'capath' => null, 'cipher' => null); 101 | $db = new DALMP\Database('latin1://root:mysql@127.0.0.1/dalmp', $ssl); 102 | 103 | try { 104 | $db->getOne('SELECT NOW()'); 105 | print_r($db->FetchMode('ASSOC')->GetRow("show variables like 'have_ssl'")); 106 | } catch (\Exception $e) { 107 | print_r($e->getMessage()); 108 | } 109 | 110 | /** 111 | * If you have SSL will get something like: 112 | Array 113 | ( 114 | [Variable_name] => have_ssl 115 | [Value] => YES 116 | ) 117 | * otherwise 118 | * 119 | Array 120 | ( 121 | [Variable_name] => have_ssl 122 | [Value] => DISABLED 123 | ) 124 | */ 125 | 126 | try { 127 | print_r($db->GetRow("show status like 'ssl_cipher'")); 128 | } catch (\Exception $e) { 129 | print_r($e->getMessage()); 130 | } 131 | 132 | /** 133 | * IF SSL working you should see something similar to this: 134 | Array 135 | ( 136 | [Variable_name] => Ssl_cipher 137 | [Value] => DHE-RSA-AES256-SHA 138 | ) 139 | * otherwise 140 | Array 141 | ( 142 | [Variable_name] => Ssl_cipher 143 | [Value] => 144 | ) 145 | */ 146 | 147 | /** 148 | * example using a socket for the connection 149 | * 150 | * charset: utf8 151 | * user: $user 152 | * password: $password 153 | * socket path: /tmp/mysql.sock 154 | * database: dalmp 155 | */ 156 | $db = new DALMP\Database("utf8://$user:$password".'@unix_socket=\tmp\mysql.sock/dalmp'); 157 | $db->debug(1); 158 | try { 159 | echo PHP_EOL, 'example using unix_socket: ', $db->getOne('SELECT NOW()'), PHP_EOL; 160 | } catch (\Exception $e) { 161 | print_r($e->getMessage()); 162 | } 163 | 164 | echo $db; // will print: DALMP :: connected to: db4, Character set: utf8, Localhost via UNIX socket,... 165 | 166 | # ----------------------------------------------------------------------------------------------------------------- 167 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 168 | -------------------------------------------------------------------------------- /examples/database/transaction_concurrent_process.php: -------------------------------------------------------------------------------- 1 | Execute('CREATE TABLE IF NOT EXISTS t_test2 (id INT NOT NULL PRIMARY KEY, credit DECIMAL(9,2)) ENGINE=InnoDB'); 15 | $db->Execute('TRUNCATE TABLE t_test2'); 16 | $db->FetchMode('ASSOC'); 17 | $db->Execute('INSERT INTO t_test2 VALUES(1, 100)'); 18 | 19 | for ($i = 1; $i <= 3; ++$i) { 20 | $pid = pcntl_fork(); 21 | 22 | if (!$pid) { 23 | switch ($i) { 24 | case 1: 25 | echo "In process: $i", PHP_EOL; 26 | $db = new DALMP\Database("utf8://$user:$password@$host:$port/dalmp"); 27 | 28 | $db->StartTrans(); 29 | $credit = $db->PGetOne('SELECT credit FROM t_test2 WHERE id=? FOR UPDATE', 1); 30 | if ($credit > 0) { 31 | $db->PExecute('UPDATE t_test2 SET credit=credit - ? WHERE id = ?', 100, 1); 32 | } 33 | echo "process $i credit: ", $db->PGetOne('SELECT credit FROM t_test2'), PHP_EOL; 34 | $rs = $db->CompleteTrans(); 35 | echo 'Transaction returned: ', (bool) $rs, PHP_EOL; 36 | exit($i); 37 | break; 38 | 39 | case 2: 40 | echo "In process: 2", PHP_EOL; 41 | $db = new DALMP\Database("utf8://$user:$password@$host:$port/dalmp"); 42 | $db->StartTrans(); 43 | $credit = $db->PGetOne('SELECT credit FROM t_test2 WHERE id=? FOR UPDATE', 1); 44 | if ($credit > 0) { 45 | $db->PExecute('UPDATE t_test2 SET credit=credit - ? WHERE id = ?', 100, 1); 46 | } 47 | echo "process $i credit: ", $db->PGetOne('SELECT credit FROM t_test2'), PHP_EOL; 48 | $rs = $db->CompleteTrans(); 49 | echo 'Transaction returned: ', (bool) $rs, PHP_EOL; 50 | exit($i); 51 | break; 52 | 53 | case 3: 54 | echo "In process: 3", PHP_EOL; 55 | $db = new DALMP\Database("utf8://$user:$password@$host:$port/dalmp"); 56 | $db->StartTrans(); 57 | $credit = $db->PGetOne('SELECT credit FROM t_test2 WHERE id=? FOR UPDATE', 1); 58 | if ($credit > 0) { 59 | $db->PExecute('UPDATE t_test2 SET credit=credit - ? WHERE id = ?', 100, 1); 60 | } 61 | echo "process $i credit: ", $db->PGetOne('SELECT credit FROM t_test2'), PHP_EOL; 62 | $rs = $db->CompleteTrans(); 63 | echo 'Transaction returned: ', (bool) $rs, PHP_EOL; 64 | exit($i); 65 | } 66 | } 67 | } 68 | 69 | while (pcntl_waitpid(0, $status) != -1) { 70 | $status = pcntl_wexitstatus($status); 71 | echo "Child $status completed", PHP_EOL; 72 | } 73 | 74 | # ------------------------------------------------------------------------------ 75 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 76 | -------------------------------------------------------------------------------- /examples/database/transactions.php: -------------------------------------------------------------------------------- 1 | debug(); 15 | 16 | $db->Execute('CREATE TABLE IF NOT EXISTS t_test (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB'); 17 | $db->Execute('TRUNCATE TABLE t_test'); 18 | $db->FetchMode('ASSOC'); 19 | 20 | $db->StartTrans(); 21 | $db->Execute('INSERT INTO t_test VALUES(1)'); 22 | $db->StartTrans(); 23 | $db->Execute('INSERT INTO t_test VALUES(2)'); 24 | print_r($db->GetAll('SELECT * FROM t_test')); 25 | $db->StartTrans(); 26 | $db->Execute('INSERT INTO t_test VALUES(3)'); 27 | print_r($db->GetAll('SELECT * FROM t_test')); 28 | $db->StartTrans(); 29 | $db->Execute('INSERT INTO t_test VALUES(7)'); 30 | print_r($db->GetALL('SELECT * FROM t_test')); 31 | $db->RollBackTrans(); 32 | print_r($db->GetALL('SELECT * FROM t_test')); 33 | $db->CompleteTrans(); 34 | $db->CompleteTrans(); 35 | $db->CompleteTrans(); 36 | 37 | # ------------------------------------------------------------------------------ 38 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 39 | -------------------------------------------------------------------------------- /examples/queue/queue.php: -------------------------------------------------------------------------------- 1 | enqueue('this is a teste')), $timer->isCli(1); 13 | 14 | echo 'dequeue all: ', print_r($queue->dequeue(), true), $timer->isCli(1); 15 | 16 | echo 'dequeue only 3: ', print_r($queue->dequeue(3), true), $timer->isCli(1); 17 | 18 | echo 'delete from queue: ', var_dump($queue->delete(63)), $timer->isCli(1); 19 | 20 | # ------------------------------------------------------------------------------ 21 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 22 | -------------------------------------------------------------------------------- /examples/sessions/REF.php: -------------------------------------------------------------------------------- 1 | regenerate_id(4); // always after your $GLOBALS 26 | } 27 | 28 | /** 29 | * get the REF stored on DB or Cache 30 | */ 31 | $rs = $sessions->getSessionRef($uid); 32 | echo '
';
33 | print_r($rs);
34 | echo '
'; 35 | echo $db->isCli(1); 36 | 37 | /** 38 | * delete the REF stored on DB or Cache 39 | */ 40 | $rs = $sessions->delSessionRef(1); 41 | echo $db->isCli(1); 42 | @$_SESSION['test']++; 43 | echo $_SESSION['test']; 44 | echo $db->isCli(1); 45 | 46 | # ----------------------------------------------------------------------------------------------------------------- 47 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 48 | -------------------------------------------------------------------------------- /examples/sessions/curl.php: -------------------------------------------------------------------------------- 1 | =200 && $httpcode<300) ? true :false; 29 | } 30 | } 31 | 32 | /** 33 | * benchmark for sessions 34 | */ 35 | for ($i=0; $i < 100; $i++) { 36 | for ($j=0; $j < 30; $j++) { 37 | echo checkSite($url,1).PHP_EOL; 38 | } 39 | @unlink('/tmp/cookie.txt'); 40 | } 41 | 42 | # ----------------------------------------------------------------------------------------------------------------- 43 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 44 | -------------------------------------------------------------------------------- /examples/sessions/sessions-redis.php: -------------------------------------------------------------------------------- 1 | getSessionRef($GLOBALS['UID'])) { 23 | // user is online 24 | exit('user already logged'); 25 | } else { 26 | $sessions->regenerate_id(true); 27 | } 28 | 29 | /** 30 | * You can use $_SESSIONS like always 31 | */ 32 | $_SESSIONS['foo'] = 'bar'; 33 | 34 | echo session_id(); 35 | # ----------------------------------------------------------------------------------------------------------------- 36 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL, 'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 37 | -------------------------------------------------------------------------------- /examples/sessions/sessions.php: -------------------------------------------------------------------------------- 1 | regenerate_id(4); 35 | } 36 | 37 | $_SESSION['test'] = 1 + @$_SESSION['test']; 38 | 39 | $rs = $db->FetchMode('ASSOC')->PGetRow('SELECT * FROM dalmp_sessions WHERE ref=?', $GLOBALS['UID']); 40 | print_r($rs); 41 | 42 | echo $db->isCli(1),session_id().$db->isCli(1),$_SESSION['test']; 43 | 44 | # ----------------------------------------------------------------------------------------------------------------- 45 | echo PHP_EOL,str_repeat('-', 80),PHP_EOL,'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL; 46 | -------------------------------------------------------------------------------- /examples/sessions/sessions_1.php: -------------------------------------------------------------------------------- 1 | regenerate_id(4); 16 | } 17 | 18 | $_SESSION['test'] = 1 + @$_SESSION['test']; 19 | 20 | echo $_SESSION['test']; 21 | 22 | echo session_id(); 23 | 24 | echo '
';
25 | # -----------------------------------------------------------------------------------------------------------------
26 | echo PHP_EOL, str_repeat('-', 80), PHP_EOL, 'Time: ',$timer->getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL;
27 | 


--------------------------------------------------------------------------------
/examples/sessions/sqlite-encryption.php:
--------------------------------------------------------------------------------
 1 | getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL;
65 | 


--------------------------------------------------------------------------------
/examples/sessions/sqliteSessions.php:
--------------------------------------------------------------------------------
 1 | getPageLoadTime(),' - Memory: ',$timer->getMemoryUsage(1),PHP_EOL,str_repeat('-', 80),PHP_EOL;
30 | 


--------------------------------------------------------------------------------
/examples/world.sql.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nbari/DALMP/49f74eb5b61a79d396c10ff58a9311f3e6f2f0c5/examples/world.sql.gz


--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
 1 | 
 2 | 
 3 |   
 4 |     
 5 |   
 6 |   
 7 |     
 8 |       tests/test_cache_disk.php
 9 |     
10 |     
11 |       tests/test_cache_memcache.php
12 |     
13 |     
14 |       tests/test_cache_redis.php
15 |     
16 |     
17 |       tests/test_sessions_memcache.php
18 |     
19 |     
20 |       tests/test_sessions_redis.php
21 |     
22 |     
23 |       tests/test_sessions_mysql.php
24 |     
25 |     
26 |       tests/test_dalmp.php
27 |     
28 |     
29 |       tests/test_dalmp_cache_memcache.php
30 |     
31 |     
32 |       tests/test_dalmp_cache_redis.php
33 |     
34 |     
35 |       tests/test_dalmp_cache_disk.php
36 |     
37 |   
38 | 
39 | 


--------------------------------------------------------------------------------
/src/DALMP/Cache.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | class Cache
13 | {
14 | 
15 |     /**
16 |      * CacheInterface instance
17 |      *
18 |      * @var CacheInterface
19 |      * @access private
20 |      */
21 |     private $cache_object;
22 | 
23 |     public function __construct(Cache\CacheInterface $object)
24 |     {
25 |         $this->cache_object = $object;
26 |     }
27 | 
28 |     public function __call($method, $args)
29 |     {
30 |         if (!method_exists($this->cache_object, $method)) {
31 |             throw new \Exception("Undefined method {$method}");
32 |         }
33 | 
34 |         return call_user_func_array(array($this->cache_object, $method), $args);
35 |     }
36 | 
37 | }
38 | 


--------------------------------------------------------------------------------
/src/DALMP/Cache/APC.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | class APC implements CacheInterface
13 | {
14 |     protected $cache;
15 | 
16 |     /**
17 |      * Constructor
18 |      *
19 |      * @param string $host
20 |      * @param int    $port
21 |      * @param int    $timeout
22 |      * @param int    $compress
23 |      */
24 |     public function __construct()
25 |     {
26 |         if (!extension_loaded('apc') && !ini_get('apc.enabled')) {
27 |             throw new \Exception(__CLASS__ . ': APC PECL extension not loaded or enabled!');
28 |         }
29 |     }
30 | 
31 |     /**
32 |      * Store data at the server
33 |      *
34 |      * @param string $key
35 |      * @param string $value
36 |      * @param int    $expire time in seconds(default is 0 meaning unlimited)
37 |      */
38 |     public function set($key, $value, $expire = 0)
39 |     {
40 |         return apc_store($key, $value, $expire);
41 |     }
42 | 
43 |     /**
44 |      * Retrieve item from the server
45 |      *
46 |      * @param string $key
47 |      */
48 |     public function Get($key)
49 |     {
50 |         return apc_fetch($key);
51 |     }
52 | 
53 |     /**
54 |      * Delete item from the server
55 |      *
56 |      * @param string $key
57 |      */
58 |     public function Delete($key)
59 |     {
60 |         return apc_delete($key);
61 |     }
62 | 
63 |     /**
64 |      * Flush cache
65 |      */
66 |     public function Flush()
67 |     {
68 |         return apc_clear_cache('user');
69 |     }
70 | 
71 |     /**
72 |      * Get cache stats
73 |      */
74 |     public function Stats()
75 |     {
76 |         return apc_cache_info();
77 |     }
78 | 
79 |     /**
80 |      * X execute/call custom methods
81 |      *
82 |      * @return cache object
83 |      */
84 |     public function X()
85 |     {
86 |         return $this;
87 |     }
88 | 
89 | }
90 | 


--------------------------------------------------------------------------------
/src/DALMP/Cache/CacheInterface.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | interface CacheInterface
13 | {
14 |     /**
15 |      * Store data at the server
16 |      *
17 |      * @param  string $key
18 |      * @param  string $value
19 |      * @param  int    $ttl   time in seconds(default is 0 meaning unlimited)
20 |      * @return this
21 |      */
22 |     public function Set($key, $value, $ttl = 0);
23 | 
24 |     /**
25 |      * Retrieve item from the server
26 |      *
27 |      * @param  string $key
28 |      * @return mixed
29 |      */
30 |     public function Get($key);
31 | 
32 |     /*
33 |      * Delete item from the server
34 |      *
35 |      * @param  string $key
36 |      * @return bool
37 |      */
38 |     public function Delete($key);
39 | 
40 |     /**
41 |      * Flush cache
42 |      *
43 |      * @return bool
44 |      */
45 |     public function Flush();
46 | 
47 |     /**
48 |      * Get cache stats
49 |      *
50 |      * @return bool
51 |      */
52 |     public function Stats();
53 | 
54 |     /**
55 |      * X execute/call custom methods
56 |      *
57 |      * @return cache object
58 |      */
59 |     public function X();
60 | 
61 | }
62 | 


--------------------------------------------------------------------------------
/src/DALMP/Cache/Memcache.php:
--------------------------------------------------------------------------------
  1 | 
  8 |  * @package DALMP
  9 |  * @license BSD License
 10 |  * @version 3.0.3
 11 |  */
 12 | class Memcache implements CacheInterface
 13 | {
 14 |     private $host = '127.0.0.1';
 15 |     private $port = 11211;
 16 |     private $timeout = 1;
 17 |     private $compress = false;
 18 |     protected $cache;
 19 | 
 20 |     /**
 21 |      * Constructor
 22 |      *
 23 |      * @param string $host
 24 |      * @param int    $port
 25 |      * @param int    $timeout
 26 |      * @param int    $compress
 27 |      */
 28 |     public function __construct()
 29 |     {
 30 |         $args = func_get_args();
 31 | 
 32 |         if ($args) {
 33 |             $this->host = isset($args[0]) ? $args[0] : '127.0.0.1';
 34 |             $this->port = isset($args[1]) ? (int) $args[1] : 11211;
 35 |             $this->timeout = isset($args[2]) ? (int) $args[2] : 1;
 36 |             if (isset($args[3])) {
 37 |                 $this->compress = MEMCACHE_COMPRESSED;
 38 |             }
 39 |         }
 40 |     }
 41 | 
 42 |     /**
 43 |      * Store data at the server
 44 |      *
 45 |      * @param string $key
 46 |      * @param string $value
 47 |      * @param int    $expire time in seconds(default is 0 meaning unlimited)
 48 |      */
 49 |     public function Set($key, $value, $expire = 0)
 50 |     {
 51 |         if ($this->connect()) {
 52 |             ($this->compress === false) && $this->cache->setCompressThreshold(0);
 53 | 
 54 |             return $this->cache->set($key, $value, $this->compress, $expire);
 55 |         } else {
 56 |             return false;
 57 |         }
 58 |     }
 59 | 
 60 |     /**
 61 |      * Retrieve item from the server
 62 |      *
 63 |      * @param string $key
 64 |      */
 65 |     public function Get($key)
 66 |     {
 67 |         return $this->connect() ? $this->cache->get($key) : false;
 68 |     }
 69 | 
 70 |     /**
 71 |      * Delete item from the server
 72 |      *
 73 |      * @param string $key
 74 |      */
 75 |     public function Delete($key)
 76 |     {
 77 |         return $this->connect() ? $this->cache->delete($key) : false;
 78 |     }
 79 | 
 80 |     /**
 81 |      * Flush cache
 82 |      */
 83 |     public function Flush()
 84 |     {
 85 |         return $this->connect() ? $this->cache->flush() : false;
 86 |     }
 87 | 
 88 |     /**
 89 |      * Get cache stats
 90 |      */
 91 |     public function Stats()
 92 |     {
 93 |         return $this->connect() ? $this->cache->getStats() : false;
 94 |     }
 95 | 
 96 |     /**
 97 |      * X execute/call custom methods
 98 |      *
 99 |      * @return cache object
100 |      */
101 |     public function X()
102 |     {
103 |         return $this->connect() ? $this->cache : false;
104 |     }
105 | 
106 |     /**
107 |      * try to establish a connection
108 |      */
109 |     private function connect()
110 |     {
111 |         if ($this->cache instanceof MemCache) {
112 |             return true;
113 |         } else {
114 |             if (!extension_loaded('memcache')) {
115 |                 throw new \Exception(__CLASS__ . 'Memcache PECL extension not loaded! - http://pecl.php.net/package/memcache');
116 |             }
117 | 
118 |             $memcache = new \Memcache();
119 | 
120 |             /**
121 |              * if a / found try to connect via socket
122 |              */
123 |             if (strpos($this->host, '/') !== false) {
124 |                 return $this->cache = $memcache->connect($this->host) ? $memcache : false;
125 |             } else {
126 |                 return $this->cache = $memcache->connect($this->host, $this->port, $this->timeout) ? $memcache : false;
127 |             }
128 |         }
129 |     }
130 | 
131 | }
132 | 


--------------------------------------------------------------------------------
/src/DALMP/Cache/Redis.php:
--------------------------------------------------------------------------------
  1 | 
  8 |  * @package DALMP
  9 |  * @license BSD License
 10 |  * @version 3.0.3
 11 |  */
 12 | class Redis implements CacheInterface
 13 | {
 14 |     private $host = '127.0.0.1';
 15 |     private $port = 6379;
 16 |     private $timeout = 1;
 17 |     protected $cache;
 18 | 
 19 |     /**
 20 |      * Constructor
 21 |      *
 22 |      * @param string $host
 23 |      * @param int    $port
 24 |      * @param int    $timeout
 25 |      */
 26 |     public function __construct()
 27 |     {
 28 |         $args = func_get_args();
 29 | 
 30 |         if ($args) {
 31 |             $this->host = isset($args[0]) ? $args[0] : '127.0.0.1';
 32 |             $this->port = isset($args[1]) ? (int) $args[1] : 6379;
 33 |             $this->timeout = isset($args[2]) ? (int) $args[2] : 1;
 34 |         }
 35 |     }
 36 | 
 37 |     /**
 38 |      * Store data at the server
 39 |      *
 40 |      * @param string $key
 41 |      * @param string $value
 42 |      * @param int    $expire time in seconds(default is 0 meaning unlimited)
 43 |      */
 44 |     public function set($key, $value, $expire = 0)
 45 |     {
 46 |         if ($this->connect()) {
 47 |             if ($expire == 0 || $expire == -1) {
 48 |                 return (bool) $this->cache->set($key, serialize($value));
 49 |             } else {
 50 |                 return (bool) $this->cache->setex($key, $expire, serialize($value));
 51 |             }
 52 |         } else {
 53 |             return false;
 54 |         }
 55 |     }
 56 | 
 57 |     /**
 58 |      * Retrieve item from the server
 59 |      *
 60 |      * @param string $key
 61 |      */
 62 |     public function Get($key)
 63 |     {
 64 |         return $this->connect() ? unserialize($this->cache->get($key)) : false;
 65 |     }
 66 | 
 67 |     /**
 68 |      * Delete item from the server
 69 |      *
 70 |      * @param string $key
 71 |      */
 72 |     public function Delete($key)
 73 |     {
 74 |         return $this->connect() ? (bool) $this->cache->delete($key) : false;
 75 |     }
 76 | 
 77 |     /**
 78 |      * Flush cache
 79 |      */
 80 |     public function Flush()
 81 |     {
 82 |         return $this->connect() ? (bool) $this->cache->flushDB() : false;
 83 |     }
 84 | 
 85 |     /**
 86 |      * Get cache stats
 87 |      */
 88 |     public function Stats()
 89 |     {
 90 |         return $this->connect() ? $this->cache->info() : false;
 91 |     }
 92 | 
 93 |     /**
 94 |      * X execute/call custom methods
 95 |      *
 96 |      * @return cache object
 97 |      */
 98 |     public function X()
 99 |     {
100 |         return $this->connect() ? $this->cache : false;
101 |     }
102 | 
103 |     /**
104 |      * try to establish a connection
105 |      */
106 |     private function connect()
107 |     {
108 |         if ($this->cache instanceof Redis) {
109 |             return true;
110 |         } else {
111 |             if (!extension_loaded('redis')) {
112 |                 throw new \Exception(__CLASS__ . 'redis extension not loaded! - http://github.com/nicolasff/phpredis');
113 |             }
114 | 
115 |             $redis = new \Redis();
116 |             try {
117 |                 /**
118 |                  * if a / found try to connect via socket
119 |                  */
120 |                 if (strpos($this->host, '/') !== false) {
121 |                     return $this->cache = $redis->connect($this->host) ? $redis : false;
122 |                 } else {
123 |                     return $this->cache = $redis->connect($this->host, $this->port, $this->timeout) ? $redis : false;
124 |                 }
125 |             } catch (\RedisException $e) {
126 |                 trigger_error('ERROR ->' . __METHOD__ . $e->getMessage(), E_USER_NOTICE);
127 | 
128 |                 return false;
129 |             }
130 |         }
131 |     }
132 | 
133 | }
134 | 


--------------------------------------------------------------------------------
/src/DALMP/DI.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | class DI extends abstractDI
13 | {
14 |     public function __construct()
15 |     {
16 |         $this->c['database'] = $this->share(function() {
17 |             $obj = new \ReflectionClass('DALMP\Database');
18 | 
19 |             return $obj->newInstanceArgs(func_get_args());
20 |         });
21 | 
22 |         $this->c['cache_memcache'] = $this->share(function() {
23 |             $obj = new \ReflectionClass('DALMP\Cache\Memcache');
24 | 
25 |             return $obj->newInstanceArgs(func_get_args());
26 |         });
27 | 
28 |         $this->c['cache_redis'] = $this->share(function() {
29 |             $obj = new \ReflectionClass('DALMP\Cache\Redis');
30 | 
31 |             return $obj->newInstanceArgs(func_get_args());
32 |         });
33 | 
34 |         $this->c['cache_disk'] = $this->share(function() {
35 |             $obj = new \ReflectionClass('DALMP\Cache\Disk');
36 | 
37 |             return $obj->newInstanceArgs(func_get_args());
38 |         });
39 | 
40 |         $this->c['cache'] = $this->share(function($backend) {
41 |             return new Cache($backend);
42 |         });
43 | 
44 |         $this->c['sessions_memcache'] = $this->share(function() {
45 |             $obj = new \ReflectionClass('DALMP\Sessions\Memcache');
46 | 
47 |             return $obj->newInstanceArgs(func_get_args());
48 |         });
49 | 
50 |         $this->c['sessions_redis'] = $this->share(function() {
51 |             $obj = new \ReflectionClass('DALMP\Sessions\Redis');
52 | 
53 |             return $obj->newInstanceArgs(func_get_args());
54 |         });
55 | 
56 |         $this->c['sessions_mysql'] = $this->share(function() {
57 |             $obj = new \ReflectionClass('DALMP\Sessions\MySQL');
58 | 
59 |             return $obj->newInstanceArgs(func_get_args());
60 |         });
61 | 
62 |         $this->c['sessions'] = $this->share(function($backend) {
63 |             return new Sessions($backend);
64 |         });
65 | 
66 |     }
67 | 
68 | }
69 | 


--------------------------------------------------------------------------------
/src/DALMP/Loader.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | class Loader
13 | {
14 |     public static function autoload($className)
15 |     {
16 |         $className = ltrim($className, '\\');
17 |         $fileName = DALMP_DIR . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
18 |         if (is_readable($fileName)) {
19 |             require $fileName;
20 |         }
21 |     }
22 | 
23 |     public static function register()
24 |     {
25 |         spl_autoload_register(array('DALMP\Loader', 'autoload'));
26 |     }
27 | 
28 | }
29 | 


--------------------------------------------------------------------------------
/src/DALMP/Queue.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | class Queue
13 | {
14 |     /**
15 |      * QueueInterface instance
16 |      *
17 |      * @var QueueInterface
18 |      * @access private
19 |      */
20 |     private $cache_object;
21 | 
22 |     public function __construct(Queue\QueueInterface $object)
23 |     {
24 |         $this->cache_object = $object;
25 |     }
26 | 
27 |     public function __call($method, $args)
28 |     {
29 |         if (!method_exists($this->cache_object, $method)) {
30 |             throw new \Exception("Undefined method {$method}");
31 |         }
32 | 
33 |         return call_user_func_array(array($this->cache_object, $method), $args);
34 |     }
35 | 
36 | }
37 | 


--------------------------------------------------------------------------------
/src/DALMP/Queue/Gearman.php:
--------------------------------------------------------------------------------
  1 | 
  8 |  * @package DALMP
  9 |  * @license BSD License
 10 |  * @version 3.0.3
 11 |  */
 12 | class Gearman implements QueueInterface
 13 | {
 14 |     /**
 15 |      * queue name
 16 |      *
 17 |      * @var string
 18 |      */
 19 |     private $queue_name;
 20 | 
 21 |     /**
 22 |      * gearman host
 23 |      * @var string
 24 |      */
 25 |     private $host;
 26 | 
 27 |     /**
 28 |      * gearman port
 29 |      *
 30 |      * @var int
 31 |      */
 32 |     private $port;
 33 | 
 34 |     /**
 35 |      * Constructor
 36 |      *
 37 |      * @param string $filename
 38 |      * @param string $queue
 39 |      * @param string $enc_key
 40 |      */
 41 |     public function __construct($queue_name = 'dalmp_queue', $host = '127.0.0.1', $port = 4730)
 42 |     {
 43 |         $this->host = $host;
 44 |         $this->port = $port;
 45 |         $this->queue_name = $queue_name;
 46 |     }
 47 | 
 48 |     /**
 49 |      * enqueue
 50 |      *
 51 |      * @param string $value
 52 |      * @return boolean
 53 |      */
 54 |     public function enqueue($value)
 55 |     {
 56 |         $gm = new \GearmanClient();
 57 |         $gm->addServer($this->host, $this->port);
 58 |         $gm->queue_name = $this->queue_name;
 59 | 
 60 |         if ($gm->ping('ping')) {
 61 |             $job_handle = $gmclient->doBackground($this->queue_name, json_encode($value), md5($value));
 62 | 
 63 |             return ($this->gmclient->returnCode() != GEARMAN_SUCCESS) ? false : true;
 64 |         } else {
 65 |             return false;
 66 |         }
 67 |     }
 68 | 
 69 |     /**
 70 |      * dequeue
 71 |      *
 72 |      * @param string $key
 73 |      */
 74 |     public function dequeue($limit = false)
 75 |     {
 76 |         $gm= new \GermanWorker();
 77 |         $gm->addServer($this->host, $this->port);
 78 |         $gm->addFunction($this->queue_name, XXX);
 79 |     }
 80 | 
 81 |     /**
 82 |      * delete element from queue
 83 |      *
 84 |      * @param string $value
 85 |      */
 86 |     public function delete($key)
 87 |     {
 88 |     }
 89 | 
 90 |     /**
 91 |      *
 92 |      * X execute/call custom methods
 93 |      *
 94 |      * @return queue object
 95 |      */
 96 |     public function X()
 97 |     {
 98 |         return $this->gmclient;
 99 |     }
100 | 
101 | }
102 | 


--------------------------------------------------------------------------------
/src/DALMP/Queue/QueueInterface.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | interface QueueInterface
13 | {
14 |     /**
15 |      * enqueue
16 |      *
17 |      * @param string $value
18 |      * @return boolean
19 |      */
20 |     public function enqueue($value);
21 | 
22 |     /**
23 |      * dequeue
24 |      *
25 |      * @param int $limit returns {$limit} entries on the queue in ASC order
26 |      * @return array
27 |      */
28 |     public function dequeue($limit = false);
29 | 
30 |     /**
31 |      * delete element from queue
32 |      *
33 |      * @param string $key
34 |      * @return boolean
35 |      */
36 |     public function delete($key);
37 | 
38 |     /**
39 |      * X execute/call custom methods
40 |      *
41 |      * @return queue object
42 |      */
43 |     public function X();
44 | 
45 | }
46 | 


--------------------------------------------------------------------------------
/src/DALMP/Queue/SQLite.php:
--------------------------------------------------------------------------------
  1 | 
  8 |  * @package DALMP
  9 |  * @license BSD License
 10 |  * @version 3.0.3
 11 |  */
 12 | class SQLite implements QueueInterface
 13 | {
 14 |     /**
 15 |      * filename - Path to the SQLite database, or :memory: to use in-memory
 16 |      * database.
 17 |      *
 18 |      * @var string
 19 |      */
 20 |     private $filename;
 21 | 
 22 |     /**
 23 |      * queue name
 24 |      *
 25 |      * @var string
 26 |      */
 27 |     private $queue_name;
 28 | 
 29 |     /**
 30 |      * enc_key
 31 |      *
 32 |      * @var string
 33 |      */
 34 |     private $enc_key = false;
 35 | 
 36 |     /**
 37 |      * Constructor
 38 |      *
 39 |      * @param string $filename
 40 |      * @param string $queue
 41 |      * @param string $enc_key
 42 |      */
 43 |     public function __construct($filename, $queue_name = 'default', $enc_key = null)
 44 |     {
 45 |         $sdb = new \SQLite3($filename);
 46 |         $sdb->busyTimeout(2000);
 47 | 
 48 |         $this->filename = $filename;
 49 |         $this->queue_name = $queue_name;
 50 | 
 51 |         if ($enc_key) {
 52 |             if ($this->sdb->exec(sprintf("PRAGMA key='%s'", $enc_key))) {
 53 |                 $this->enc_key = $enc_key;
 54 |             }
 55 |         }
 56 | 
 57 |         $sdb->exec('PRAGMA synchronous=OFF; PRAGMA temp_store=MEMORY; PRAGMA journal_mode=MEMORY');
 58 |         $sdb->exec('CREATE TABLE IF NOT EXISTS queues (id INTEGER PRIMARY KEY, queue VARCHAR (64) NOT null, data TEXT, cdate DATE)');
 59 |         $sdb->busyTimeout(0);
 60 |         $sdb->close();
 61 |     }
 62 | 
 63 |     /**
 64 |      * enqueue
 65 |      *
 66 |      * @param string $value
 67 |      * @return boolean
 68 |      */
 69 |     public function enqueue($value)
 70 |     {
 71 |         $sdb = new \SQLite3($this->filename);
 72 |         $sdb->busyTimeout(2000);
 73 |         if ($this->enc_key) {
 74 |             $sdb->exec(sprintf("PRAGMA key='%s'", $enc_key));
 75 |         }
 76 | 
 77 |         $stmt = $sdb->prepare('INSERT INTO queues VALUES (null, ?, ?, ?)');
 78 |         $stmt->bindValue(1, $this->queue_name, SQLITE3_TEXT);
 79 |         $stmt->bindValue(2, base64_encode($value), SQLITE3_TEXT);
 80 |         $stmt->bindValue(3, @date('Y-m-d H:i:s'), SQLITE3_BLOB);
 81 | 
 82 |         if (!$stmt->execute()) {
 83 |             throw new \ErrorException(sprintf('Could not save: [ %s ] on queue [ %s ] in [ %s ]', $value, $this->queue_name, $this->filename));
 84 |         }
 85 | 
 86 |         $sdb->busyTimeout(0);
 87 |         $sdb->close();
 88 | 
 89 |         return true;
 90 |     }
 91 | 
 92 |     /**
 93 |      * dequeue
 94 |      *
 95 |      * @param string $key
 96 |      */
 97 |     public function dequeue($limit = false)
 98 |     {
 99 |         $sdb = new \SQLite3($this->filename);
100 |         $sdb->busyTimeout(2000);
101 |         if ($this->enc_key) {
102 |             $sdb->exec(sprintf("PRAGMA key='%s'", $enc_key));
103 |         }
104 | 
105 |         if ($limit) {
106 |             $stmt = $sdb->prepare('SELECT * FROM queues WHERE queue = ? LIMIT ?');
107 |             $stmt->bindValue(1, $this->queue_name, SQLITE3_TEXT);
108 |             $stmt->bindValue(2, $limit, SQLITE3_INTEGER);
109 |         } else {
110 |             $stmt = $sdb->prepare('SELECT * FROM queues WHERE queue = ?');
111 |             $stmt->bindValue(1, $this->queue_name, SQLITE3_TEXT);
112 |         }
113 | 
114 |         $rs = $stmt->execute();
115 | 
116 |         $rows = array();
117 | 
118 |         if ($rs) {
119 |             while ($row = $rs->fetchArray(SQLITE3_ASSOC)) {
120 |                 $rows[$row['id']] = array('id' => $row['id'], 'queue' => $row['queue'], 'data' => $row['data'], 'cdate' => $row['cdate']);
121 |             }
122 |         }
123 | 
124 |         return $rows;
125 |     }
126 | 
127 |     /**
128 |      * delete element from queue
129 |      *
130 |      * @param string $value
131 |      */
132 |     public function delete($key)
133 |     {
134 |         $sdb = new \SQLite3($this->filename);
135 |         $sdb->busyTimeout(2000);
136 |         if ($this->enc_key) {
137 |             $sdb->exec(sprintf("PRAGMA key='%s'", $enc_key));
138 |         }
139 | 
140 |         $stmt = $sdb->prepare('DELETE FROM queues WHERE queue = ? AND id = ?');
141 |         $stmt->bindValue(1, $this->queue_name, SQLITE3_TEXT);
142 |         $stmt->bindValue(2, $key, SQLITE3_INTEGER);
143 | 
144 |         $sdb->busyTimeout(0);
145 | 
146 |         return (bool) $stmt->execute();
147 |     }
148 | 
149 |     /**
150 |      *
151 |      * X execute/call custom methods
152 |      *
153 |      * @return queue object
154 |      */
155 |     public function X() {}
156 | 
157 | }
158 | 


--------------------------------------------------------------------------------
/src/DALMP/Sessions.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | class Sessions
13 | {
14 |     /**
15 |      * session_handler
16 |      *
17 |      * @access private
18 |      * @SessionHandlerInterface
19 |      */
20 |     private $session_handler;
21 | 
22 |     /**
23 |      * construct - set the sesion save handler
24 |      *
25 |      * @param SessionHandlerInterface $session_handler
26 |      * @param hash_algo               $session_hash
27 |      */
28 |     public function __construct($session_handler = false, $hash_algo = 'sha256')
29 |     {
30 |         if (!$session_handler) {
31 |             $this->session_handler = new Sessions\SQLite();
32 |         } else {
33 |             if ($session_handler instanceof \SessionHandlerInterface) {
34 |                 $this->session_handler = $session_handler;
35 |             } else {
36 |                 throw new \InvalidArgumentException((string) $session_handler . ' is not an instance of SessionHandlerInterface');
37 |             }
38 |         }
39 | 
40 |         ini_set('session.gc_maxlifetime', defined('DALMP_SESSIONS_MAXLIFETIME') ? DALMP_SESSIONS_MAXLIFETIME : get_cfg_var('session.gc_maxlifetime'));
41 |         ini_set('session.use_cookies', 1);
42 |         ini_set('session.use_only_cookies', 1);
43 |         ini_set('session.cookie_httponly', 1);
44 |         ini_set('session.use_trans_sid', 0);
45 |         ini_set('session.hash_bits_per_character', 5);
46 |         ini_set('session.hash_function', in_array($hash_algo, hash_algos()) ? $hash_algo : 1);
47 |         ini_set('session.name', 'DALMP');
48 | 
49 |         session_set_save_handler($this->session_handler, true);
50 |         session_start();
51 |     }
52 | 
53 |     /**
54 |      * regenerate id - regenerate sessions and create a fingerprint, helps to
55 |      * prevent HTTP session hijacking attacks.
56 |      *
57 |      * @param  boolean $use_IP
58 |      * @return boolean
59 |      */
60 |     public function regenerate_id($use_IP = true)
61 |     {
62 |         $fingerprint = @$_SERVER['HTTP_ACCEPT'] . @$_SERVER['HTTP_USER_AGENT'] . @$_SERVER['HTTP_ACCEPT_ENCODING'] . @$_SERVER['HTTP_ACCEPT_LANGUAGE'];
63 | 
64 |         if ($use_IP) {
65 |             $fingerprint .= @$_SERVER['REMOTE_ADDR'];
66 |         }
67 | 
68 |         $fingerprint = sha1('DALMP' . $fingerprint);
69 | 
70 |         if ((isset($_SESSION['fingerprint']) && $_SESSION['fingerprint'] != $fingerprint)) {
71 |             $_SESSION = array();
72 |             session_destroy();
73 |         }
74 | 
75 |         if (session_regenerate_id(true)) {
76 |             $_SESSION['fingerprint'] = $fingerprint;
77 | 
78 |             return true;
79 |         } else {
80 |             return false;
81 |         }
82 |     }
83 | 
84 |     /**
85 |      * to handle session Refs per session_handler
86 |      */
87 |     public function __call($method, $args)
88 |     {
89 |         if (!method_exists($this->session_handler, $method)) {
90 |             throw new \Exception("Undefined method {$method}");
91 |         }
92 | 
93 |         return call_user_func_array(array($this->session_handler, $method), $args);
94 |     }
95 | 
96 | }
97 | 


--------------------------------------------------------------------------------
/src/DALMP/Sessions/Files.php:
--------------------------------------------------------------------------------
  1 | 
  8 |  * @package DALMP
  9 |  * @license BSD License
 10 |  * @version 3.0.3
 11 |  */
 12 | class Files implements \SessionHandlerInterface
 13 | {
 14 |     /**
 15 |      * path to store sessions
 16 |      *
 17 |      * @access private
 18 |      * @var string
 19 |      */
 20 |     private $sessions_dir;
 21 | 
 22 |     /**
 23 |      * constructor
 24 |      *
 25 |      * @param string $dir
 26 |      */
 27 |     public function __construct($sessions_dir = false)
 28 |     {
 29 |         if (!$sessions_dir) {
 30 |             $sessions_dir = defined('DALMP_SESSIONS_DIR') ? DALMP_SESSIONS_DIR : '/tmp/dalmp_sessions';
 31 |         }
 32 | 
 33 |         if (!is_writable($sessions_dir)) {
 34 |             if (!is_dir($sessions_dir) && !mkdir($sessions_dir, 0700, true)) {
 35 |                 throw new \InvalidArgumentException($sessions_dir . ' not accessible');
 36 |             }
 37 |         }
 38 | 
 39 |         $this->sessions_dir = $dir;
 40 |     }
 41 | 
 42 |     public function close()
 43 |     {
 44 |         return true;
 45 |     }
 46 | 
 47 |     public function destroy($session_id)
 48 |     {
 49 |         $sess_path = sprintf('%s/%s/%s/%s', $this->sessions_dir, substr($session_id, 0, 2), substr($session_id, 2, 2),  substr($session_id, 4, 2));
 50 |         $sess_file = sprintf('%s/%s', $sess_path , "{$session_id}.sess");
 51 | 
 52 |         if (file_exists($sess_file)) {
 53 |             unlink($sess_file);
 54 |         }
 55 | 
 56 |         return true;
 57 |     }
 58 | 
 59 |     public function gc($maxlifetime)
 60 |     {
 61 |         $session_files = $this->rsearch($this->sessions_dir, '#^.*\.sess$#');
 62 | 
 63 |         foreach ($session_files as $file) {
 64 |             if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
 65 |                 unlink($file);
 66 |             }
 67 |         }
 68 | 
 69 |         return true;
 70 |     }
 71 | 
 72 |     public function open($save_path, $name)
 73 |     {
 74 |         return true;
 75 |     }
 76 | 
 77 |     public function read($session_id)
 78 |     {
 79 |         $sess_path = sprintf('%s/%s/%s/%s', $this->sessions_dir, substr($session_id, 0, 2), substr($session_id, 2, 2),  substr($session_id, 4, 2));
 80 | 
 81 |         if (!is_dir($sess_path) && !mkdir($sess_path, 0700, true)) {
 82 |             throw new \Exception("$sess_path  not accessible");
 83 |         }
 84 | 
 85 |         $sess_file = sprintf('%s/%s', $sess_path , "{$session_id}.sess");
 86 | 
 87 |         return (string) @file_get_contents($sess_file);
 88 |     }
 89 | 
 90 |     public function write($session_id, $session_data)
 91 |     {
 92 |         $sess_path = sprintf('%s/%s/%s/%s', $this->sessions_dir, substr($session_id, 0, 2), substr($session_id, 2, 2),  substr($session_id, 4, 2));
 93 | 
 94 |         if (!is_dir($sess_path) && !mkdir($sess_path, 0700, true)) {
 95 |             throw new \Exception("$sess_path  not accessible");
 96 |         }
 97 | 
 98 |         $sess_file = sprintf('%s/%s', $sess_path , "{$session_id}.sess");
 99 | 
100 |         return file_put_contents($sess_file, $session_data) === false ? false : true;
101 |     }
102 | 
103 |     /**
104 |      * getSessionsRefs
105 |      *
106 |      * @param  int   $expiry
107 |      * @return array of sessions containing any reference
108 |      */
109 |     public function getSessionsRefs($expired_sessions = false)
110 |     {
111 |         $refs = array();
112 | 
113 |         return false;
114 |     }
115 | 
116 |     /**
117 |      * getSessionRef
118 |      *
119 |      * @param  string $ref
120 |      * @return array  of session containing a specific reference
121 |      */
122 |     public function getSessionRef($ref)
123 |     {
124 |         return false;
125 |     }
126 | 
127 |     /**
128 |      * delSessionsRef - delete sessions containing a specific reference
129 |      *
130 |      * @param  string  $ref
131 |      * @return boolean
132 |      */
133 |     public function delSessionRef($ref)
134 |     {
135 |         return false;
136 |     }
137 | 
138 |     /**
139 |      * recursive dir search
140 |      *
141 |      * @param string $folder
142 |      * @param string $pattern example: '#^.*\.sess$#'
143 |      */
144 |     public function rsearch($folder, $pattern)
145 |     {
146 |         $dir = new RecursiveDirectoryIterator($folder);
147 |         $ite = new RecursiveIteratorIterator($dir);
148 |         $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
149 |         $fileList = array();
150 |         foreach ($files as $file) {
151 |             $fileList = array_merge($fileList, $file);
152 |         }
153 | 
154 |         return $fileList;
155 |     }
156 | 
157 | }
158 | 


--------------------------------------------------------------------------------
/src/DALMP/Sessions/MySQL.php:
--------------------------------------------------------------------------------
  1 | 
  8 |  * @package DALMP
  9 |  * @license BSD License
 10 |  * @version 3.0.3
 11 |  */
 12 | class MySQL implements \SessionHandlerInterface
 13 | {
 14 |     /**
 15 |      * DALMP\Database instance
 16 |      *
 17 |      * @access protected
 18 |      * @var DALMP\Database
 19 |      */
 20 |     protected $DB;
 21 | 
 22 |     /**
 23 |      * REF - field used for storing references
 24 |      *
 25 |      * @access private
 26 |      * @var mixed
 27 |      */
 28 |     private $dalmp_sessions_ref;
 29 | 
 30 |     /**
 31 |      * table to use for sessions
 32 |      * @access private
 33 |      * @var mixed
 34 |      */
 35 |     private $dalmp_sessions_table = 'dalmp_sessions';
 36 | 
 37 |     /**
 38 |      * constructor
 39 |      *
 40 |      * @param DALMP\Database $db           instance
 41 |      * @param string         $sessions_ref global variable to be stored as reference
 42 |      */
 43 |     public function __construct(\DALMP\Database $DB, $sessions_ref = 'UID')
 44 |     {
 45 |         $this->DB = $DB;
 46 |         $this->dalmp_sessions_ref = defined('DALMP_SESSIONS_REF') ? DALMP_SESSIONS_REF : $sessions_ref;
 47 | 
 48 |         if (defined('DALMP_SESSIONS_TABLE')) {
 49 |             $this->dalmp_sessions_table = DALMP_SESSIONS_TABLE;
 50 |         }
 51 |     }
 52 | 
 53 |     public function close()
 54 |     {
 55 |         return true;
 56 |     }
 57 | 
 58 |     public function destroy($session_id)
 59 |     {
 60 |         $sql = 'DELETE FROM ' . $this->dalmp_sessions_table . ' WHERE sid=?';
 61 | 
 62 |         return $this->DB->PExecute($sql, $session_id);
 63 |     }
 64 | 
 65 |     public function gc($maxlifetime)
 66 |     {
 67 |         $sql = 'DELETE FROM ' . $this->dalmp_sessions_table . ' WHERE expiry < UNIX_TIMESTAMP()';
 68 |         $this->DB->Execute($sql);
 69 | 
 70 |         $sql = 'OPTIMIZE TABLE ' . $this->dalmp_sessions_table;
 71 |         $this->DB->Execute($sql);
 72 | 
 73 |         return true;
 74 |     }
 75 | 
 76 |     public function open($save_path, $name)
 77 |     {
 78 |         return true;
 79 |     }
 80 | 
 81 |     public function read($session_id)
 82 |     {
 83 |         return ($rs = $this->DB->PGetOne('SELECT data FROM ' . $this->dalmp_sessions_table . ' WHERE sid=? AND expiry >=?', $session_id, time())) ? $rs : '';
 84 |     }
 85 | 
 86 |     public function write($session_id, $session_data)
 87 |     {
 88 |         $ref = (isset($GLOBALS[$this->dalmp_sessions_ref]) && !empty($GLOBALS[$this->dalmp_sessions_ref])) ? $GLOBALS[$this->dalmp_sessions_ref] : null;
 89 | 
 90 |         $expiry = time() + ini_get('session.gc_maxlifetime');
 91 | 
 92 |         $sql = "REPLACE INTO $this->dalmp_sessions_table (sid, expiry, data, ref) VALUES(?,?,?,?)";
 93 | 
 94 |         return $this->DB->PExecute($sql, $session_id, $expiry, $session_data, $ref);
 95 |     }
 96 | 
 97 |     /**
 98 |      * getSessionsRefs
 99 |      *
100 |      * @return array of sessions containing any reference
101 |      */
102 |     public function getSessionsRefs()
103 |     {
104 |         $refs = array();
105 | 
106 |         $db_refs = $this->DB->FetchMode('ASSOC')->GetAll("SELECT sid, ref, expiry FROM $this->dalmp_sessions_table WHERE ref IS NOT null");
107 | 
108 |         if ($db_refs) {
109 |             foreach ($db_refs as $value) {
110 |                 $refs[$value['sid']] = array($value['ref'] => $value['expiry']);
111 |             }
112 |         }
113 | 
114 |         return $refs;
115 |     }
116 | 
117 |     /**
118 |      * getSessionRef
119 |      *
120 |      * @param  string $ref
121 |      * @return array  of session containing a specific reference
122 |      */
123 |     public function getSessionRef($ref)
124 |     {
125 |         $refs = array();
126 | 
127 |         $db_refs = $this->DB->PGetall('SELECT sid, ref, expiry FROM dalmp_sessions WHERE ref=?', $ref);
128 | 
129 |         if ($db_refs) {
130 |             foreach ($db_refs as $value) {
131 |                 $refs[$value['sid']] = array($value['ref'] => $value['expiry']);
132 |             }
133 |         }
134 | 
135 |         return $refs;
136 |     }
137 | 
138 |     /**
139 |      * delSessionRef - delete sessions containing a specific reference
140 |      *
141 |      * @param  string  $ref
142 |      * @return boolean
143 |      */
144 |     public function delSessionRef($ref)
145 |     {
146 |         return $this->DB->PExecute('DELETE FROM ' . $this->dalmp_sessions_table . ' WHERE ref=?', $ref);
147 |     }
148 | 
149 | }
150 | 


--------------------------------------------------------------------------------
/src/DALMP/abstractDI.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | abstract class abstractDI
13 | {
14 | 
15 |     /**
16 |      * Container for the classes
17 |      *
18 |      * @var array
19 |      */
20 |     protected $c = array();
21 | 
22 |     /**
23 |      * Share the classes
24 |      *
25 |      * @param  Closure $callable A closure to wrap for uniqueness
26 |      * @return Closure The wrapped closure
27 |      */
28 |     public function share(\Closure $callable)
29 |     {
30 |         return function () use ($callable) {
31 |             static $object = null;
32 |             if (is_null($object)) {
33 |                 $object = call_user_func_array($callable, func_get_args());
34 |             }
35 | 
36 |             return $object;
37 |         };
38 |     }
39 | 
40 |     /**
41 |      * Dispatch the classes
42 |      *
43 |      * @param  string    $name
44 |      * @param  string    $args
45 |      * @return chainable object
46 |      */
47 |     public function __call($name, $args)
48 |     {
49 |         if (!isset($this->c[$name])) {
50 |             throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $name));
51 |         }
52 | 
53 |         $c = $this->c[$name];
54 | 
55 |         return  ($c instanceof \Closure) ? call_user_func_array($c, $args) : $c;
56 |     }
57 | 
58 |     /**
59 |      * return the Closures
60 |      *
61 |      * @param string Closure name
62 |      * @return closure
63 |      */
64 |     public function __get($key)
65 |     {
66 |         if (array_key_exists($key, $this->c)) {
67 |             return $this->c[$key];
68 |         }
69 |     }
70 | 
71 |     /**
72 |      * Add an object to the container
73 |      *
74 |      * To share (load and later use) this can be used:
75 |      * $di->addObject('name', $di->share(function () {
76 |      *   return new Foo();
77 |      * }));
78 |      *
79 |      * @param  string $name
80 |      * @param  object $object
81 |      * @return true   on success exception on failure
82 |      */
83 |     public function addObject($name, $object)
84 |     {
85 |         if (isset($this->c[$name])) {
86 |             throw new \InvalidArgumentException(sprintf('Class "%s" already defined.', $name));
87 |         }
88 | 
89 |         return $this->c[$name] = $object;
90 |     }
91 | 
92 | }
93 | 


--------------------------------------------------------------------------------
/src/dalmp.php:
--------------------------------------------------------------------------------
 1 | 
 8 |  * @package DALMP
 9 |  * @license BSD License
10 |  * @version 3.0.3
11 |  */
12 | 
13 | if (defined('DALMP_DIR')) {
14 |     return;
15 | } else {
16 |     define('DALMP_DIR', dirname(__FILE__));
17 | }
18 | 
19 | require_once DALMP_DIR . '/DALMP/Loader.php';
20 | 
21 | Loader::register();
22 | 


--------------------------------------------------------------------------------
/tests/test_cache_base.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @package DALMP
 8 |  * @license BSD License
 9 |  * @version 3.0
10 |  */
11 | abstract class test_cache_base extends PHPUnit_Framework_TestCase
12 | {
13 |     abstract public function testAttributes();
14 | 
15 |     public function testSet()
16 |     {
17 |         $tmp_string = '';
18 |         foreach (range(1,100) as $id) {
19 |             $this->assertTrue($this->cache->set("test_dalmp_key_{$id}", "val_{$id}"));
20 |             /**
21 |              * test expiry TTL
22 |              */
23 |             $this->assertTrue($this->cache->set("test_dalmp_key_ttl_{$id}", "val_{$id}", 2));
24 |             $tmp_string .= sha1($id);
25 |         }
26 | 
27 |         $this->assertTrue($this->cache->set("test_dalmp_key_tmp_string", $tmp_string));
28 |     }
29 | 
30 |     /**
31 |      * @medium
32 |      */
33 |     public function testGet()
34 |     {
35 |         /**
36 |          * wait 2 seconds to let keys expire
37 |          */
38 |         sleep(2);
39 |         $tmp_string = '';
40 |         foreach (range(1,100) as $id) {
41 |             $this->assertEquals("val_{$id}", $this->cache->get("test_dalmp_key_{$id}"));
42 |             $this->assertEquals(false, $this->cache->get("test_dalmp_key_ttl_{$id}"));
43 |             $tmp_string .= sha1($id);
44 |         }
45 | 
46 |         $this->assertEquals($tmp_string, $this->cache->get("test_dalmp_key_tmp_string"));
47 |     }
48 | 
49 |     public function testDelete()
50 |     {
51 |         foreach (range(1,100) as $id) {
52 |             $this->assertEquals(true, $this->cache->delete("test_dalmp_key_{$id}"));
53 |         }
54 | 
55 |         $this->assertEquals(true, $this->cache->delete("test_dalmp_key_tmp_string"));
56 |     }
57 | 
58 |     public function testFlush()
59 |     {
60 |         $this->cache->set('x', 'y');
61 |         $this->asserttrue($this->cache->Flush());
62 |         $this->assertEquals(false, $this->cache->get('x'));
63 |     }
64 | 
65 | }
66 | 


--------------------------------------------------------------------------------
/tests/test_cache_disk.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_cache_disk extends test_cache_base
14 | {
15 |     /**
16 |      * Cache instance
17 |      *
18 |      * @var Cache
19 |      */
20 |     protected $cache;
21 | 
22 |     public function setUp()
23 |     {
24 |         $this->cache = new DALMP\Cache\Disk('/tmp/test_dalmp_disk');
25 |     }
26 | 
27 |     public function testAttributes()
28 |     {
29 |         $this->assertClassHasAttribute('cache_dir', 'DALMP\Cache\Disk');
30 |     }
31 | 
32 |     public function testX()
33 |     {
34 |         $this->assertContainsOnlyInstancesOf('DALMP\Cache\Disk', array($this->cache));
35 |     }
36 | 
37 | }
38 | 


--------------------------------------------------------------------------------
/tests/test_cache_memcache.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_cache_memcache extends test_cache_base
14 | {
15 |     /**
16 |      * Cache instance
17 |      *
18 |      * @var Cache
19 |      */
20 |     protected $cache;
21 | 
22 |     public function setUp()
23 |     {
24 |         if (!extension_loaded('memcache')) {
25 |             $this->markTestSkipped('The memcache extension is not available.');
26 |         }
27 |         $this->cache = new DALMP\Cache\Memcache;
28 |     }
29 | 
30 |     public function testAttributes()
31 |     {
32 |         $this->assertClassHasAttribute('host', 'DALMP\Cache\Memcache');
33 |         $this->assertClassHasAttribute('port', 'DALMP\Cache\Memcache');
34 |         $this->assertClassHasAttribute('timeout', 'DALMP\Cache\Memcache');
35 |         $this->assertClassHasAttribute('compress', 'DALMP\Cache\Memcache');
36 |         $this->assertClassHasAttribute('cache', 'DALMP\Cache\Memcache');
37 |     }
38 | 
39 |     public function testX()
40 |     {
41 |         $this->assertContainsOnlyInstancesOf('DALMP\Cache\Memcache', array($this->cache));
42 |     }
43 | 
44 | }
45 | 


--------------------------------------------------------------------------------
/tests/test_cache_redis.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_cache_redis extends test_cache_base
14 | {
15 |     /**
16 |      * Cache instance
17 |      *
18 |      * @var Cache
19 |      */
20 |     protected $cache;
21 | 
22 |     public function setUp()
23 |     {
24 |         if (!extension_loaded('redis')) {
25 |             $this->markTestSkipped('The redis extension is not available.');
26 |         }
27 |         $this->cache = new DALMP\Cache\Redis;
28 |     }
29 | 
30 |     public function testAttributes()
31 |     {
32 |         $this->assertClassHasAttribute('host', 'DALMP\Cache\Redis');
33 |         $this->assertClassHasAttribute('port', 'DALMP\Cache\Redis');
34 |         $this->assertClassHasAttribute('timeout', 'DALMP\Cache\Redis');
35 |         $this->assertClassHasAttribute('cache', 'DALMP\Cache\Redis');
36 |     }
37 | 
38 |     public function testX()
39 |     {
40 |         $this->assertContainsOnlyInstancesOf('DALMP\Cache\Redis', array($this->cache));
41 |     }
42 | 
43 |     public function testPing()
44 |     {
45 |         $this->assertEquals('+PONG', $this->cache->X()->ping());
46 | 
47 |         $count = 1000;
48 |         while ($count --) {
49 |             $this->assertEquals('+PONG', $this->cache->X()->ping());
50 |         }
51 |     }
52 | 
53 | }
54 | 


--------------------------------------------------------------------------------
/tests/test_dalmp_cache_disk.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_dalmp_cache_disk extends test_dalmp_cache_base
14 | {
15 |     public function setUp()
16 |     {
17 |         if (!extension_loaded('mysqli')) {
18 |             $this->markTestSkipped('The mysqli extension is not available.');
19 |         }
20 | 
21 |         /**
22 |          * read DSN from phpunit.xml
23 |          */
24 |         $this->db = new DALMP\Database($GLOBALS['DSN']);
25 |         $this->db->useCache(new DALMP\Cache(new DALMP\Cache\Disk('/tmp/test_dalmp_disk')));
26 |     }
27 | 
28 | }
29 | 


--------------------------------------------------------------------------------
/tests/test_dalmp_cache_memcache.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_dalmp_cache_memcache extends test_dalmp_cache_base
14 | {
15 |     public function setUp()
16 |     {
17 |         if (!extension_loaded('mysqli')) {
18 |             $this->markTestSkipped('The mysqli extension is not available.');
19 |         }
20 | 
21 |         /**
22 |          * read DSN from phpunit.xml
23 |          */
24 |         $this->db = new DALMP\Database($GLOBALS['DSN']);
25 |         $this->db->useCache(new DALMP\Cache(new DALMP\Cache\Memcache()));
26 |     }
27 | 
28 | }
29 | 


--------------------------------------------------------------------------------
/tests/test_dalmp_cache_redis.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_dalmp_cache_redis extends test_dalmp_cache_base
14 | {
15 |     public function setUp()
16 |     {
17 |         if (!extension_loaded('mysqli')) {
18 |             $this->markTestSkipped('The mysqli extension is not available.');
19 |         }
20 | 
21 |         /**
22 |          * read DSN from phpunit.xml
23 |          */
24 |         $this->db = new DALMP\Database($GLOBALS['DSN']);
25 |         $this->db->useCache(new DALMP\Cache(new DALMP\Cache\Redis()));
26 |     }
27 | 
28 | }
29 | 


--------------------------------------------------------------------------------
/tests/test_sessions_base.php:
--------------------------------------------------------------------------------
  1 | 
  7 |  * @package DALMP
  8 |  * @license BSD License
  9 |  * @version 3.0
 10 |  */
 11 | abstract class test_sessions_base extends PHPUnit_Framework_TestCase
 12 | {
 13 |     abstract public function testAttributes();
 14 | 
 15 |     public function getSessionData($i)
 16 |     {
 17 |         return "{$i}. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
 18 |     }
 19 | 
 20 |     public function testOpen()
 21 |     {
 22 |         $this->asserttrue($this->sess->open(true, true));
 23 |     }
 24 | 
 25 |     /**
 26 |      * @depends testOpen
 27 |      */
 28 |     public function testWrite()
 29 |     {
 30 |         for ($i = 0; $i < 100; $i++) {
 31 |             $this->asserttrue($this->sess->write(sha1("sid_{$i}"), $this->getSessionData($i)));
 32 |         }
 33 |     }
 34 | 
 35 |     /**
 36 |      * @depends testWrite
 37 |      */
 38 |     public function testRead()
 39 |     {
 40 |         for ($i = 0; $i < 100; $i++) {
 41 |             $this->assertEquals($this->getSessionData($i), $this->sess->read(sha1("sid_{$i}")));
 42 |         }
 43 |     }
 44 | 
 45 |     /**
 46 |      * @depends testWrite
 47 |      */
 48 |     public function testDestroy()
 49 |     {
 50 |         for ($i = 0; $i < 100; $i++) {
 51 |             $this->asserttrue($this->sess->destroy(sha1("sid_{$i}")));
 52 |         }
 53 |     }
 54 | 
 55 |     /**
 56 |      * @depends testOpen
 57 |      */
 58 |     public function testClose()
 59 |     {
 60 |         $this->asserttrue($this->sess->close());
 61 |     }
 62 | 
 63 |     /**
 64 |      * @depends testClose
 65 |      */
 66 |     public function testGC()
 67 |     {
 68 |         $this->asserttrue($this->sess->gc(true));
 69 |     }
 70 | 
 71 |     public function testWriteRef()
 72 |     {
 73 |         for ($i = 0; $i < 100; $i++) {
 74 |             $GLOBALS['UID'] = sha1($i);
 75 |             $this->asserttrue($this->sess->write(sha1("sid_{$i}"), $this->getSessionData($i)));
 76 |         }
 77 |     }
 78 | 
 79 |     public function testGetSessionsRefs()
 80 |     {
 81 |         $this->assertEquals(100, count($this->sess->getSessionsRefs()));
 82 |     }
 83 | 
 84 |     public function testGetSessionRef()
 85 |     {
 86 |         for ($i = 0; $i < 100; $i++) {
 87 |             $this->assertEquals(1, count($this->sess->getSessionRef(sha1($i))));
 88 |         }
 89 |     }
 90 | 
 91 |     public function testDelSessionRef()
 92 |     {
 93 |         for ($i = 0; $i < 100; $i++) {
 94 |             $this->asserttrue($this->sess->delSessionRef(sha1($i)));
 95 |             $this->assertEquals(array(), $this->sess->getSessionRef(sha1($i)));
 96 |         }
 97 |     }
 98 | 
 99 | }
100 | 


--------------------------------------------------------------------------------
/tests/test_sessions_memcache.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_sessions_memcache extends test_sessions_base
14 | {
15 |     /**
16 |      * SessionHandler instance
17 |      *
18 |      * @var sess
19 |      */
20 |     protected $sess;
21 | 
22 |     public function setUp()
23 |     {
24 |         if (!extension_loaded('memcache')) {
25 |             $this->markTestSkipped('The memcache extension is not available.');
26 |         }
27 |         $this->sess = new DALMP\Sessions\Memcache(new DALMP\Cache\Memcache);
28 |     }
29 | 
30 |     public function testAttributes()
31 |     {
32 |         $this->assertClassHasAttribute('cache', 'DALMP\Sessions\Memcache');
33 |         $this->assertClassHasAttribute('cache_ref_key', 'DALMP\Sessions\Memcache');
34 |         $this->assertClassHasAttribute('dalmp_sessions_ref', 'DALMP\Sessions\Memcache');
35 |         $this->assertClassHasAttribute('dalmp_sessions_key', 'DALMP\Sessions\Memcache');
36 |     }
37 | 
38 | }
39 | 


--------------------------------------------------------------------------------
/tests/test_sessions_mysql.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_sessions_mysql extends test_sessions_base
14 | {
15 |     /**
16 |      * SessionHandler instance
17 |      *
18 |      * @var sess
19 |      */
20 |     protected $sess;
21 | 
22 |     public function setUp()
23 |     {
24 |         if (!extension_loaded('mysqli')) {
25 |             $this->markTestSkipped('The mysqli extension is not available.');
26 |         }
27 | 
28 |         /**
29 |          * read DSN from phpunit.xml
30 |          */
31 |         $db = new DALMP\Database($GLOBALS['DSN']);
32 |         $this->sess = new DALMP\Sessions\MySQL($db);
33 |     }
34 | 
35 |     public function testAttributes()
36 |     {
37 |         $this->assertClassHasAttribute('DB', 'DALMP\Sessions\MySQL');
38 |         $this->assertClassHasAttribute('dalmp_sessions_ref', 'DALMP\Sessions\MySQL');
39 |         $this->assertClassHasAttribute('dalmp_sessions_table', 'DALMP\Sessions\MySQL');
40 |     }
41 | 
42 | }
43 | 


--------------------------------------------------------------------------------
/tests/test_sessions_redis.php:
--------------------------------------------------------------------------------
 1 | 
 9 |  * @package DALMP
10 |  * @license BSD License
11 |  * @version 3.0
12 |  */
13 | class test_sessions_redis extends test_sessions_base
14 | {
15 |     /**
16 |      * SessionHandler instance
17 |      *
18 |      * @var sess
19 |      */
20 |     protected $sess;
21 | 
22 |     public function setUp()
23 |     {
24 |         if (!extension_loaded('redis')) {
25 |             $this->markTestSkipped('The redis extension is not available.');
26 |         }
27 |         $this->sess = new DALMP\Sessions\Redis(new DALMP\Cache\Redis);
28 |     }
29 | 
30 |     public function testAttributes()
31 |     {
32 |         $this->assertClassHasAttribute('cache', 'DALMP\Sessions\Redis');
33 |         $this->assertClassHasAttribute('cache_ref_key', 'DALMP\Sessions\Redis');
34 |         $this->assertClassHasAttribute('dalmp_sessions_ref', 'DALMP\Sessions\Redis');
35 |         $this->assertClassHasAttribute('dalmp_sessions_key', 'DALMP\Sessions\Redis');
36 |     }
37 | 
38 | }
39 | 


--------------------------------------------------------------------------------