Compare commits

...
16 Commits
Author SHA1 Message Date
ahwelp f2084c161d Don't try to propagate when there is nothin to propagate 2026-08-24 14:09:58 -03:00
ahwelp 29d05b84e6 Adding a Prettier README.md 2026-08-19 11:00:28 -03:00
ahwelp 46dd177be9 Moving the relations to a dedicated Namespace 2026-08-19 10:59:49 -03:00
ahwelp 64bce1da47 Some identation, documentation and minor changes 2026-08-19 10:58:35 -03:00
ahwelp ac04cd02f4 Some identation and minor changes 2026-08-19 10:57:31 -03:00
ahwelp bd2f3bddff Some identation and documentation 2026-08-19 10:55:16 -03:00
ahwelp c2f00d6c21 Changes 2023-04-25 18:09:41 +00:00
Artur Welp 7b2f03e139 Atualizar 'composer.json' 2023-02-07 13:25:12 +00:00
ahwelp 94793fa252 First steps to fix the softdelete issue 2023-01-24 13:33:59 +00:00
ahwelp 2bfd6ec104 First steps to fix the softdelete issue 2023-01-24 13:33:27 +00:00
ahwelp bfab5fc27e Changing $data param to be a array for default 2023-01-24 13:32:46 +00:00
ahwelp 5f9316e15e Adding each method 2023-01-24 13:32:08 +00:00
ahwelp 0a768bb649 Mudanças 2022-04-05 20:04:28 +00:00
ahwelp 477f3696ba Mudanças 2022-04-05 20:03:21 +00:00
Your Name 5835106252 Mudanças 2022-03-29 16:14:12 +00:00
ahwelp 1669a4279d Changes 2022-03-23 22:01:58 +00:00
14 changed files with 860 additions and 365 deletions
+215 -3
View File
@@ -1,3 +1,215 @@
# ORM # urfat-orm
aasasf
ddd A lightweight, zero-dependency PHP ORM with Laravel/Eloquent-inspired syntax. Built on top of PDO, it supports multiple named connections, soft deletes, timestamps, eager loading, and pivot table relationships.
---
## Installation
```bash
composer install
```
No external dependencies. PHP 8.0+ required.
---
## Setup
```php
require 'vendor/autoload.php';
use ORM\Connection;
use ORM\Connections;
// Using the factory helper
$pdo = Connection::open('pgsql', 'dbname=mydb host=localhost', 'user', 'pass', 'myprefix_');
// Or register a raw PDO
$pdo = new PDO("pgsql:dbname=mydb;host=localhost", 'user', 'pass');
$pdo->prefix = 'myprefix_';
Connections::addConnection($pdo); // 'default'
Connections::addConnection($pdo, 'secondary'); // named connection
```
Supported drivers: `pgsql`, `mysql`, `sqlite`, `firebird`, `oracle`, `mssql`.
---
## Defining a Model
```php
use ORM\Entity;
class User extends Entity {
const _tableName = 'users';
const _connectionName = 'default'; // optional, defaults to 'default'
const _softdelete = true; // filters deleted_at IS NULL on all queries
const _timestamps = true; // auto-sets created_at / updated_at on save
const _ignore = ['password_confirm']; // excluded from INSERT / UPDATE
const _idPolice = [ // optional custom ID strategy
'type' => 'nextval',
'min' => 500,
'max' => 9999,
'step' => 10,
];
protected function posts() {
return $this->hasMany(Post::class, 'user_id');
}
protected function country() {
return $this->belongsTo(Country::class, 'country_id', 'id');
}
protected function roles() {
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}
}
```
---
## Features
### CRUD
```php
// Create
$user = new User(['name' => 'Alice', 'email' => 'alice@example.com']);
$user->save(); // INSERT; $user->id is populated after
// Read
$user = User::findOne(42);
$user = User::findOne(['email' => ['=', 'alice@example.com']]);
$users = User::findAll();
$users = User::findMany(['active' => ['=', 1]], ['*'], ['LIMIT' => 10, 'OFFSET' => 0]);
$n = User::count(['active' => ['=', 1]]);
// Update
$user->name = 'Bob';
$user->save(); // UPDATE because $user->id exists
// Delete
$user->delete(); // soft-delete if _softdelete=true, otherwise hard-delete
$user->purge(); // always hard-delete
$user->restore(); // clears deleted_at (soft-delete models only)
```
Criteria format: `['column' => ['operator', value]]`
Supported operators: `=`, `<`, `>`, `<=`, `>=`, `IN`, `LIKE`
### Soft Delete
When `_softdelete = true`, all `findAll`, `findOne`, `findMany`, and `count` calls automatically append `WHERE deleted_at IS NULL`. Pass `true` as the last argument to include trashed records:
```php
$all = User::findAll(['*'], [], true); // includes soft-deleted
$trashed = User::findOne(42, ['*'], true);
```
### Timestamps
When `_timestamps = true`, `created_at` and `updated_at` are set on construction and `updated_at` is refreshed on every `save()`.
### Relationships
| Method | Description |
|---|---|
| `hasOne(Class, $remoteField)` | One child record keyed by local id |
| `hasMany(Class, $remoteField)` | Many child records keyed by local id |
| `belongsTo(Class, $localField, $remoteField)` | Parent record |
| `belongsToMany(Class, $pivot, $localKey, $remoteKey)` | Many-to-many via pivot |
| `belongsToManyExtended(...)` | Many-to-many via pivot; returns pivot rows with foreign object in `->childElement` |
```php
// Lazy load (fires a query on access)
$posts = $user->posts()->get();
$country = $user->country; // magic __get shorthand
// Eager load on a Collection
$users = User::findAll()->with(['posts', 'country']);
// Eager load on a single Entity
$user->with(['posts', 'country']);
```
### Multiple Named Connections
```php
Connections::addConnection($pdo1); // 'default'
Connections::addConnection($pdo2, 'analytics'); // 'analytics'
class Event extends Entity {
const _connectionName = 'analytics';
}
```
### Custom ID Strategy (`_idPolice`)
When `type = 'nextval'` the ORM computes the next ID from `MAX(id)` before inserting, respecting `min`, `max`, and `step`. Useful for databases without auto-increment sequences.
### Raw Query Helpers (`DBInstance`)
For queries that don't fit the Entity API:
```php
use ORM\DBInstance;
// Single record with prepared statement
$row = DBInstance::getRecord('users', ['email' => ['=', $email]]);
// Multiple records
$rows = DBInstance::getRecords('users', ['active' => ['=', 1]], ['id', 'name'], ['LIMIT' => 50]);
// Free SQL
$rows = DBInstance::getRecordsSql("SELECT * FROM {users} WHERE created_at > ?", [$date]);
// Insert and get last id
$id = DBInstance::insertRecord('logs', ['action' => 'login', 'user_id' => 1]);
// Update a single field
DBInstance::setField('users', 'active', 0, $id);
// Direct query
DBInstance::execute("UPDATE {users} SET score = score + 1 WHERE id = ?", [$id]);
```
Table names always use `{tableName}` placeholder syntax so the connection prefix is applied automatically.
### SQL Tracing
```php
$pdo->traceSQL = true; // prints every query to stdout
```
---
## Known Bugs
| # | Location | Description |
|---|---|---|
| 1 | `Collection::with()` | After the Relations namespace refactor, the `switch` class-name checks still use old names (`ORM\HasMany`, etc.) — all branches fall to `default`, which works but is inaccurate |
| 2 | `Entity::findMany()`, `Entity::count()` | When no criteria are given and `_softdelete = true`, `AND deleted_at IS NULL` is appended without a preceding `WHERE`, producing invalid SQL |
| 3 | `Entity` constructor / `update()` | Timestamp format uses `date('Y-m-d h:m:s')``h` is 12-hour clock and the second `m` is month; should be `date('Y-m-d H:i:s')` |
| 4 | `Entity::__get()` | Returns `0` for any undefined property, silently masking typos |
| 5 | `DBInstance::queryOne()` | When called with `$data`, it delegates to `queryPrepare()` which calls `fetchAll()` and returns an array, not a single object |
| 6 | `DBInstance::setField()` | Uses PHP string interpolation `{$table}` instead of the ORM's `{tableName}` syntax, so the connection prefix is never applied |
| 7 | `Entity::findMany()` | Values are interpolated directly into SQL (no prepared statements), making this method unsafe for user-supplied input |
---
## To Do
- [ ] Fix `findMany()` and `count()` soft-delete `WHERE` clause when no other criteria exist
- [ ] Fix timestamp format (`H:i:s`)
- [ ] Fix `Collection::with()` class-name checks after Relations namespace refactor
- [ ] Fix `DBInstance::setField()` table prefix placeholder
- [ ] Fix `DBInstance::queryOne()` to actually return one record
- [ ] Make `findMany()` use prepared statements
- [ ] `Collection::with()` — use a bulk `IN (...)` query instead of one query per item (N+1 problem)
- [ ] Relations cannot be iterated in Mustache / template engines (magic `__get` on `Entity` calls `->get()` but templates can't iterate the result transparently)
- [ ] `__get()` should return `null` instead of `0` for undefined properties
- [ ] Add formal test suite (PHPUnit)
- [ ] Support `ORDER BY` in `findAll()` and `findMany()`
- [ ] Support `whereNull` / `whereNotNull` criteria shorthand
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"name" : "urfat/orm", "name" : "inforsistemas/orm",
"description" : "Diferent ORM", "description" : "Diferent ORM",
"type" : "library", "type" : "library",
"authors" : [ "authors" : [
-24
View File
@@ -1,24 +0,0 @@
<?php
namespace ORM;
class BelongsTo {
private $foreignObject;
private $localField;
private $remoteField;
private $localElement;
function __construct($foreignObject, $localField, $remoteField = 'id', $localElement) {
$this->foreignObject = $foreignObject;
$this->localField = $localField;
$this->remoteField = $remoteField;
$this->localElement = $localElement;
}
function get() {
return $this->foreignObject::findOne(Array($this->remoteField => Array('=', $this->localElement->{$this->localField})));
}
}
+21 -9
View File
@@ -26,13 +26,11 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
} }
// https://www.php.net/manual/en/class.iteratoraggregate.php // https://www.php.net/manual/en/class.iteratoraggregate.php
public function getIterator() public function getIterator(): \Generator
{ {
return (function () { foreach ($this->items as $key => $val) {
while (list($key, $val) = each($this->items)) { yield $key => $val;
yield $key => $val; }
}
})();
} }
// https://www.php.net/manual/en/class.arrayaccess.php // https://www.php.net/manual/en/class.arrayaccess.php
@@ -79,7 +77,6 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
// Collection specific methods // Collection specific methods
// //
function get($forceCollection = false) function get($forceCollection = false)
{ {
if (sizeof($this->items) == 1 && !$forceCollection) { if (sizeof($this->items) == 1 && !$forceCollection) {
@@ -100,11 +97,13 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
switch (get_class($relation)) { switch (get_class($relation)) {
case 'ORM\HasMany': case 'ORM\HasMany':
$this->items[$key]->$connection = $this->items[$key]->$connection()->get();
break; break;
case 'ORM\HasOne': case 'ORM\HasOne':
$this->items[$key]->$connection = $this->items[$key]->$connection()->get();
break; break;
case 'ORM\BelongsTo': case 'ORM\BelongsTo':
$searchs['belongsTo'][] = []; $this->items[$key]->$connection = $this->items[$key]->$connection()->get();
break; break;
case 'ORM\BelongsToMany': case 'ORM\BelongsToMany':
$this->items[$key]->$connection = $this->items[$key]->$connection()->get(); $this->items[$key]->$connection = $this->items[$key]->$connection()->get();
@@ -119,7 +118,7 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
} }
} }
return $this->items; return $this;
} }
function first() function first()
@@ -128,4 +127,17 @@ class Collection implements \Countable, \IteratorAggregate, \ArrayAccess
return $this->items[0]; return $this->items[0];
} }
} }
/**
* Iterate over the colletion
*
* @param mixed $function
* @return void
*/
function each($function)
{
foreach($this->items as $item){
$function($item);
}
}
} }
+66 -18
View File
@@ -3,29 +3,72 @@
namespace ORM; namespace ORM;
/** /**
* \PDO generator class * \PDO generator class
* *
* This code is based on the TConnection.php class on the Adianti Framework * This code is based on the TConnection.php class on the Adianti Framework
* *
* @license http://www.adianti.com.br/framework-license * @license http://www.adianti.com.br/framework-license
* *
*/ */
class Connection { class Connection
{
private function __construct() { /**
* Available Database Drivers
* @var array
*/
const array drivers = ["pgsql", "mysql", "sqlite", "ibase", "oci8", "mssq"];
}
public static function open($connection_info = null) { /**
* Private constructor
* This class will not exist, it only encapsulate logic
*/
private function __construct(){ }
$user = isset($connection_info['user']) ? $connection_info['user'] : NULL; /**
$pass = isset($connection_info['pass']) ? $connection_info['pass'] : NULL; * Open a new connection
$name = isset($connection_info['name']) ? $connection_info['name'] : NULL; *
$host = isset($connection_info['host']) ? $connection_info['host'] : NULL; * You need to pass a connection configuration in a Object/Array
$driver = isset($connection_info['driver']) ? $connection_info['driver'] : NULL; *
$port = isset($connection_info['port']) ? $connection_info['port'] : NULL; * user
$prefix = isset($connection_info['prefix']) ? $connection_info['prefix'] : ''; * pass
* name
* host
* driver
* - pgsql (Postgres)
* - mysql (MySQL)
* - sqlite (SQLite)
* - ibase (Firebird)
* - oci8 (Oracle)
* - mssql SQLServer
* port
* prefix
*
* @param mixed $connectionInfo
*
* @return \PDO
*/
public static function open(mixed $connectionInfo = []): \PDO
{
if (is_array($connectionInfo)) {
$connectionInfo = (object) $connectionInfo;
}
if(!isset($connectionInfo->driver)){
throw new \Exception("Driver not defined");
}
$user = isset($connectionInfo->user) ? $connectionInfo->user : NULL;
$pass = isset($connectionInfo->pass) ? $connectionInfo->pass : NULL;
$name = isset($connectionInfo->name) ? $connectionInfo->name : NULL;
$host = isset($connectionInfo->host) ? $connectionInfo->host : NULL;
$driver = isset($connectionInfo->driver) ? $connectionInfo->driver : NULL;
$port = isset($connectionInfo->port) ? $connectionInfo->port : NULL;
$prefix = isset($connectionInfo->prefix) ? $connectionInfo->prefix : '';
$traceSQL = isset($connectionInfo->traceSQL) ? $connectionInfo->traceSQL : false;
switch ($driver) { switch ($driver) {
case 'pgsql': case 'pgsql':
@@ -49,8 +92,13 @@ class Connection {
$conn = new \PDO("mssql:host={$host},1433;dbname={$name}", $user, $pass); $conn = new \PDO("mssql:host={$host},1433;dbname={$name}", $user, $pass);
break; break;
} }
$conn->prefix = $prefix; $conn->prefix = $prefix;
$conn->driver = $driver;
$conn->traceSQL = $traceSQL;
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn; return $conn;
} }
+97 -76
View File
@@ -2,10 +2,19 @@
namespace ORM; namespace ORM;
/**
* Summary of DBInstance
*/
class DBInstance class DBInstance
{ {
private static function addPrefix($sql, $instance = 'default') /**
* Summary of addPrefix
* @param string $sql
* @param string $instance
* @return string
*/
private static function addPrefix(string $sql, string $instance = 'default')
{ {
$con = Connections::getConnection($instance); $con = Connections::getConnection($instance);
@@ -25,14 +34,11 @@ class DBInstance
* *
* This method will execute a SQL on the database * This method will execute a SQL on the database
* *
* @ctag DBInstance::execute($sql); * @param string $sql The SQL to be executed
* @ctag DBInstance::execute($sql, []); * @param array $data Pass the info to be replaced on the query_prepare
* * @param string $instance Select the connection to execute
* @param String $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute
*/ */
public static function execute($sql, $data = null, $instance = 'default') public static function execute(string $sql, Array $data = Array(), string $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); $sql = self::addPrefix($sql, $instance);
if ($data) { if ($data) {
@@ -43,12 +49,12 @@ class DBInstance
} }
} }
/* /**
* * Summary of lastInsert
* @ctag DBInstance::lastInsert(); * @param string $instance
* @return mixed
*/ */
public static function lastInsert(string $instance = 'default')
public static function lastInsert($instance = 'default')
{ {
$con = Connections::getConnection($instance); $con = Connections::getConnection($instance);
return $con->lastInsertId(); return $con->lastInsertId();
@@ -59,43 +65,42 @@ class DBInstance
* *
* This method will execute a SQL and return a pointer to the resultset * This method will execute a SQL and return a pointer to the resultset
* *
* @ctag DBInstance::query($sql); * @param string $sql The SQL to be executed
* @ctag DBInstance::query($sql, []); * @param array $data Pass the info to be replaced on the query_prepare
* @param string $instance Select the connection to execute
* *
* @param String $sql The SQL to be executed * @return mixed A pointer for a foreach loop
* @param Array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute
*
* @return pointer A pointer for a foreach loop
*/ */
public static function query($sql, $data = null, $instance = 'default') public static function query(string $sql, array $data = [], $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); $sql = self::addPrefix($sql, $instance);
if ($data) { if ($data) {
return self::queryPrepare($sql, $data, $instance); return self::queryPrepare($sql, $data, $instance);
} else { } else {
$con = Connections::getConnection($instance); try {
return $con->query($sql, \PDO::FETCH_OBJ); $con = Connections::getConnection($instance);
return $con->query($sql, \PDO::FETCH_OBJ);
} catch (\Throwable $th) {
var_dump($th); die;
}
} }
} }
/** /**
* queryOne * queryOne
* *
* @ctag DBInstance::queryOne($sql);
* @ctag DBInstance::queryOne($sql, []);
*
* This method will execute a SQL and return the first featched register * This method will execute a SQL and return the first featched register
* *
* @param String $sql The SQL to be executed * @param string $sql The SQL to be executed
* @param Array $data Pass the info to be replaced on the query_prepare * @param array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute * @param string $instance Select the connection to execute
* *
* @return stdClass A object with the record info * @return \stdClass A object with the record info
*/ */
public static function queryOne($sql, $data = null, $instance = 'default') public static function queryOne(string $sql, Array $data = null, string $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); $sql = self::addPrefix($sql, $instance);
if ($data) { if ($data) {
@@ -111,16 +116,12 @@ class DBInstance
* *
* This method will execute get a register from a table * This method will execute get a register from a table
* *
* @ctag DBInstance::getRecord($table); * @param string $table The table to be searched
* @ctag DBInstance::getRecord($table, []); * @param array $data Pass the info to be replaced on the query_prepare
* @ctag DBInstance::getRecord($table, [], []); * @param array $select Info to be put on the SELECT part of the query
* @param string $instance Select the connection to execute
* *
* @param String $table The table to be searched * @return mixed A object with the record info
* @param Array $data Pass the info to be replaced on the query_prepare
* @param Array $select Info to be put on the SELECT part of the query
* @param String $instance Select the connection to execute
*
* @return stdClass A object with the record info
*/ */
public static function getRecord($table, $data = array(), $select = array('*'), $instance = 'default') public static function getRecord($table, $data = array(), $select = array('*'), $instance = 'default')
{ {
@@ -163,14 +164,11 @@ class DBInstance
* *
* This method will get a record from the database using SQL * This method will get a record from the database using SQL
* *
* @ctag DBInstance::getRecordSql($sql); * @param string $sql The SQL to be executed
* @ctag DBInstance::getRecordSql($sql, []); * @param array $data Pass the info to be replaced on the query_prepare
* @param string $instance Select the connection to execute
* *
* @param String $sql The SQL to be executed * @return mixed A object with the record info
* @param Array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute
*
* @return stdClass A object with the record info
*/ */
public static function getRecordSql($sql, $data = null, $instance = 'default') public static function getRecordSql($sql, $data = null, $instance = 'default')
{ {
@@ -189,18 +187,20 @@ class DBInstance
* *
* This method will get records from the database * This method will get records from the database
* *
* @ctag DBInstance::getRecords($table); * @param string $table The table to be searched
* @ctag DBInstance::getRecords($table, []); * @param array $data Pass the info to be replaced on the query_prepare
* @param array $select Info to be put on the SELECT part of the query
* @param string $instance Select the connection to execute
* *
* @param String $table The table to be searched * @return array A object with the record info
* @param Array $data Pass the info to be replaced on the query_prepare
* @param Array $select Info to be put on the SELECT part of the query
* @param String $instance Select the connection to execute
*
* @return stdClass A object with the record info
*/ */
public static function getRecords($table, $data = null, $select = array('*'), $limits = array(), $instance = 'default') public static function getRecords($table, $data = array(), $select = array('*'), $limits = array(), $instance = 'default')
{ {
if(empty($data)){
$data = array("1" => ['=', 1]);
}
$pointer = self::getRecordsPointer($table, $data, $select, $limits, $instance); $pointer = self::getRecordsPointer($table, $data, $select, $limits, $instance);
$elements = array(); $elements = array();
@@ -216,15 +216,12 @@ class DBInstance
* *
* This method will get records from the database * This method will get records from the database
* *
* @ctag DBInstance::getRecordsPointer($table); * @param string $table The table to be searched
* @ctag DBInstance::getRecordsPointer($table, []); * @param array $data Pass the info to be replaced on the query_prepare
* @param array $select Info to be put on the SELECT part of the query
* @param string $instance Select the connection to execute
* *
* @param String $table The table to be searched * @return mixed A object with the record info
* @param Array $data Pass the info to be replaced on the query_prepare
* @param Array $select Info to be put on the SELECT part of the query
* @param String $instance Select the connection to execute
*
* @return stdClass A object with the record info
*/ */
public static function getRecordsPointer($table, $data = array(), $select = array('*'), $limits = array(), $instance = 'default') public static function getRecordsPointer($table, $data = array(), $select = array('*'), $limits = array(), $instance = 'default')
{ {
@@ -273,14 +270,11 @@ class DBInstance
* *
* This method will get records from the database * This method will get records from the database
* *
* @ctag DBInstance::getRecordsSql($sql); * @param string $sql The SQL to be executed
* @ctag DBInstance::getRecordsSql($sql, []); * @param array $data Pass the info to be replaced on the query_prepare
* @param string $instance Select the connection to execute
* *
* @param String $sql The SQL to be executed * @return array Array with objects representing the database data
* @param Array $data Pass the info to be replaced on the query_prepare
* @param String $instance Select the connection to execute
*
* @return Array Array with objects representing the database data
*/ */
public static function getRecordsSql($sql, $data = null, $instance = 'default') public static function getRecordsSql($sql, $data = null, $instance = 'default')
{ {
@@ -301,6 +295,14 @@ class DBInstance
return $elements; return $elements;
} }
/**
* Summary of insertRecord
* @param string $table
* @param array $data
* @param string $connection
*
* @return int
*/
public static function insertRecord($table, $data = array(), $connection = 'default') public static function insertRecord($table, $data = array(), $connection = 'default')
{ {
@@ -327,14 +329,33 @@ class DBInstance
$sql = "INSERT INTO {" . $table . "} ($first_argument) VALUES ($second_argument)"; $sql = "INSERT INTO {" . $table . "} ($first_argument) VALUES ($second_argument)";
DBInstance::execute($sql, $insert_data, $connection); DBInstance::execute($sql, $insert_data, $connection);
return self::lastInsert($connection);
} }
/**
* Summary of queryPrepare
* @param string $sql
* @param array $data
* @param string $instance
* @return mixed
*/
public static function queryPrepare($sql, $data = array(), $instance = 'default') public static function queryPrepare($sql, $data = array(), $instance = 'default')
{ {
$sql = self::addPrefix($sql, $instance); try {
$con = Connections::getConnection($instance); $sql = self::addPrefix($sql, $instance);
$statement = $con->prepare($sql); $con = Connections::getConnection($instance);
$statement->execute($data);
return $statement->fetchAll(\PDO::FETCH_OBJ); if($con->traceSQL){
echo "$sql \n";
}
$statement = $con->prepare($sql);
$statement->execute($data);
return $statement->fetchAll(\PDO::FETCH_OBJ);
} catch (\Throwable $th) {
error_log($th);
}
} }
} }
+270 -165
View File
@@ -2,12 +2,19 @@
namespace ORM; namespace ORM;
abstract class Entity { use ORM\Relations\HasOne;
use ORM\Relations\HasMany;
use ORM\Relations\BelongsTo;
use ORM\Relations\BelongsToMany;
use ORM\Relations\BelongsToManyExtended;
abstract class Entity
{
const _tableName = ''; const _tableName = '';
const _connectionName = 'default'; const _connectionName = 'default';
const _softdelete = false; const _softdelete = false;
const _ignore = Array( const _ignore = array(
'classname', 'classname',
'_properties', '_properties',
'_ignore', '_ignore',
@@ -15,9 +22,10 @@ abstract class Entity {
'_timestamps', '_timestamps',
'_softdelete', '_softdelete',
'_tableName', '_tableName',
'_idPolice' '_idPolice',
'_ignore'
); );
const _properties = Array(); const _properties = array();
/* /*
* [type] = nextval| manual | empty is the default * [type] = nextval| manual | empty is the default
@@ -25,30 +33,50 @@ abstract class Entity {
* [min] = minumul value allowed * [min] = minumul value allowed
* [step] = increment by n each id * [step] = increment by n each id
*/ */
const _idPolice = Array(); const _idPolice = array();
function __construct($assignment = '')
{
@$this->_ignore = array_merge((array) $this->_ignore, self::_ignore);
function __construct() {
if (isset($this->_timestamps) && $this->_timestamps) { if (isset($this->_timestamps) && $this->_timestamps) {
$this->created_at = date('Y-m-d h:m:s'); $this->created_at = date('Y-m-d h:m:s');
$this->updated_at = date('Y-m-d h:m:s'); $this->updated_at = date('Y-m-d h:m:s');
} }
// Mass Assign
if (is_array($assignment)) {
$this->charge($assignment);
}
} }
public function __set($property, $value) { public function __set($property, $value)
{
if (in_array($property, static::_ignore)) { if (in_array($property, static::_ignore)) {
return; return;
} }
$this->$property = $value; $this->$property = $value;
} }
public function __get($key) { public function __get($key)
{
// The __get might be a connection. So return it
if (method_exists($this, $key)) {
return $this->$key();
}
// Empty is bad for this kind of dynamicity
if (!isset($this->$key)) { if (!isset($this->$key)) {
return 0; return 0;
} }
return $this->toArray()[$key];
// There is a key. So return it
return $this->$key;
} }
public function __toString() { public function __toString()
{
if (isset($this->name)) { if (isset($this->name)) {
return $this->name; return $this->name;
} }
@@ -58,15 +86,36 @@ abstract class Entity {
return static::class; return static::class;
} }
public function charge($payload) { // public function __call($name, $arguments){ }
foreach (static::_properties as $key => $property) {
public function charge($payload)
{
$properties = [];
foreach (get_object_vars($this) as $key => $property) {
if (substr($key, 0, 1) != '_') {
$properties[] = $key;
}
}
$elements = array_diff(array_merge($properties, static::_properties), self::_ignore);
foreach ($elements as $key => $property) {
if ($property == 'id' && !isset($payload[$property])) {
continue;
}
if (empty($payload[$property])) {
continue;
}
$this->$property = $payload[$property]; $this->$property = $payload[$property];
} }
return []; return [];
} }
public static function get_properties() { public static function get_properties()
$properties = Array(); {
$properties = array();
foreach (static::_properties as $propertie) { foreach (static::_properties as $propertie) {
$obj = new \stdClass(); $obj = new \stdClass();
$obj->data = $propertie; $obj->data = $propertie;
@@ -75,7 +124,8 @@ abstract class Entity {
return json_encode($properties); return json_encode($properties);
} }
public function save() { public function save()
{
if (isset($this->id)) { if (isset($this->id)) {
$this->update(); $this->update();
} else { } else {
@@ -83,9 +133,10 @@ abstract class Entity {
} }
} }
private function update() { private function update()
{
//First check if the record exist. If not, we might have a idPolice //First check if the record exist. If not, we might have a idPolice
if (!DBInstance::queryOne("SELECT id FROM {" . static::_tableName . "} WHERE id = ?", Array($this->id))) { if (!DBInstance::queryOne("SELECT id FROM {" . static::_tableName . "} WHERE id = ?", array($this->id))) {
$this->create(); $this->create();
return; return;
} }
@@ -96,9 +147,13 @@ abstract class Entity {
$obj = (array) $this; $obj = (array) $this;
$update_string = ''; $update_string = '';
$update_data = Array(); $update_data = array();
$update_data['_update_id'] = $this->id; $update_data['_update_id'] = $this->id;
if (isset($this->_timestamps) && $this->_timestamps) {
$this->updated_at = date('Y-m-d h:m:s');
}
foreach ($columns as $column) { foreach ($columns as $column) {
$update_string .= $column . " = :$column, "; $update_string .= $column . " = :$column, ";
$update_data[$column] = $obj[$column]; $update_data[$column] = $obj[$column];
@@ -110,7 +165,8 @@ abstract class Entity {
DBInstance::execute($sql, $update_data, static::_connectionName); DBInstance::execute($sql, $update_data, static::_connectionName);
} }
private function create() { private function create()
{
//First, let's verify id polices //First, let's verify id polices
//Manual and empty don't need special treatments //Manual and empty don't need special treatments
if (!empty(static::_idPolice) && static::_idPolice['type'] != 'manual') { if (!empty(static::_idPolice) && static::_idPolice['type'] != 'manual') {
@@ -119,7 +175,7 @@ abstract class Entity {
$maxVal = ($maxVal) ? $maxVal : 0; $maxVal = ($maxVal) ? $maxVal : 0;
// If the next val is smaller than the minumum value // If the next val is smaller than the minumum value
if (isset(static::_idPolice['min']) && static::_idPolice['min'] > $maxVal->id+1) { if (isset(static::_idPolice['min']) && static::_idPolice['min'] > $maxVal->id + 1) {
// The id value shpuld assume the min value // The id value shpuld assume the min value
$this->id = static::_idPolice['min']; $this->id = static::_idPolice['min'];
} else { } else {
@@ -143,7 +199,7 @@ abstract class Entity {
$first_argument = ''; $first_argument = '';
$second_argument = ''; $second_argument = '';
$insert_data = Array(); $insert_data = array();
foreach ($columns as $column) { foreach ($columns as $column) {
$first_argument .= $column . ', '; $first_argument .= $column . ', ';
@@ -164,31 +220,46 @@ abstract class Entity {
} }
} }
public function delete() {
if (isset($this->_softdelete) && $this->_softdelete) {
$this->deleted_at = date('Y-m-d h:m:s');
$this->update();
return;
}
$this->purge();
}
public function load($id = false) { public function load($id = false)
{
if (!$id) { if (!$id) {
return; return;
} }
$sql = "SELECT * FROM {" . static::_tableName . "} WHERE id = ?"; $sql = "SELECT * FROM {" . static::_tableName . "} WHERE id = ?";
$this->fill(DBInstance::queryPrepare($sql, Array($id), static::_connectionName)[0]); $this->fill(DBInstance::queryPrepare($sql, array($id), static::_connectionName)[0]);
} }
public function purge() { public function delete()
{
if (static::_softdelete) {
$this->deleted_at = date('Y-m-d h:m:s');
$this->update();
} else {
$this->purge();
}
}
public function purge()
{
$sql = "DELETE FROM {" . static::_tableName . "} WHERE id = :id"; $sql = "DELETE FROM {" . static::_tableName . "} WHERE id = :id";
DBInstance::execute($sql, Array('id' => $this->id), static::_connectionName); DBInstance::execute($sql, array('id' => $this->id), static::_connectionName);
} }
private function fill($data) { public function restore()
{
if (isset($this->_softdelete) && $this->_softdelete) {
$this->deleted_at = null;
$this->update();
} else {
throw new \Exception('Not soft deleteble');
}
}
private function fill($data)
{
$data = (array) $data; $data = (array) $data;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
@@ -206,7 +277,8 @@ abstract class Entity {
* @param Array $limits Array( 'offset'=> 10, 'limit' => 10 ) * @param Array $limits Array( 'offset'=> 10, 'limit' => 10 )
* @param boolean $trashed Bring trashed elements? * @param boolean $trashed Bring trashed elements?
*/ */
public static function findAll($select = Array('*'), $limits = Array(), $trashed = false) { public static function findAll($select = array('*'), $limits = array(), $trashed = false): Collection
{
$criteria = ''; $criteria = '';
$limits_sql = ''; $limits_sql = '';
@@ -226,14 +298,14 @@ abstract class Entity {
$sql = "SELECT $criteria FROM {" . static::_tableName . "} $limits_sql"; $sql = "SELECT $criteria FROM {" . static::_tableName . "} $limits_sql";
} }
$results = DBInstance::query($sql, Array(), static::_connectionName); $results = DBInstance::query($sql, array(), static::_connectionName);
$objects = Array(); $objects = new Collection;
foreach ($results as $value) { foreach ($results as $value) {
$static = static::class; $static = static::class;
$object = new $static; $object = new $static;
$object->fill($value); $object->fill($value);
$objects[] = $object; $objects->addItem($object);
} }
return $objects; return $objects;
} }
@@ -248,9 +320,10 @@ abstract class Entity {
* @param boolean $trashed Bring trashed registers? * @param boolean $trashed Bring trashed registers?
* *
*/ */
public static function count($criterias = Array(), $trashed = false) { public static function count($criterias = array(), $trashed = false)
{
$criteria_sql = ""; $criteria_sql = "";
$criteria_data = Array(); $criteria_data = array();
foreach ($criterias as $key => $criteria) { foreach ($criterias as $key => $criteria) {
if ($criteria_sql != "") { if ($criteria_sql != "") {
$criteria_sql .= " AND "; $criteria_sql .= " AND ";
@@ -283,42 +356,58 @@ abstract class Entity {
/** /**
* Find One * Find One
* *
* @param Array/Int $criterias Array('id' => Array('in', Array(10, 20, 30))) * @param Int|String|Array $criterias Array('id' => Array('in', Array(10, 20, 30)))
* @param Array $select Array(id, fullname) * @param Array $select Array(id, fullname)
* @param Boolan $trashed true, false * @param bool $trashed true, false
*/ */
public static function findOne($criterias = Array(), $select = Array('*'), $trashed = false) { public static function findOne(
int|string|array $criterias = array(),
array $select = array('*'),
bool $trashed = false
) {
if (empty($criterias)) {
$criterias = array(1 => ['=', 1]);
}
$select_sql = ""; $select_sql = "";
$criteria_sql = ""; $criteria_sql = "";
$limits_sql = ""; $limits_sql = "";
$criteria_data = Array(); $criteria_data = array();
$limits = Array("LIMIT" => 1); $limits = array("LIMIT" => 1);
if (is_numeric($criterias)) { if (!is_array($criterias)) {
$criteria_sql = "WHERE id = ? "; $criteria_sql = "WHERE id = ? ";
$criteria_data[] = $criterias; $criteria_data[] = $criterias;
} else { } else {
foreach ($criterias as $key => $criteria) { if (!array_is_list($criterias)) {
if ($criteria_sql != "") { foreach ($criterias as $key => $criteria) {
$criteria_sql .= " AND "; if ($criteria_sql != "") {
} else { $criteria_sql .= " AND ";
$criteria_sql .= " WHERE "; } else if ($criteria_sql == "") {
} $criteria_sql .= " WHERE ";
if (is_array($criteria[1])) { } else {
$crit_temp = ''; $criteria_sql .= " ";
foreach ($criteria[1] as $crit) { }
$crit_temp .= '?, '; if (is_array($criteria[1])) {
$criteria_data[] = $crit; $crit_temp = '';
foreach ($criteria[1] as $crit) {
$crit_temp .= '?, ';
$criteria_data[] = $crit;
}
$crit_temp = rtrim($crit_temp, ', ');
$criteria_sql .= "$key $criteria[0] ($crit_temp)";
} else {
$criteria_sql .= "$key $criteria[0] (?) ";
$criteria_data[] = $criteria[1];
} }
$crit_temp = rtrim($crit_temp, ', ');
$criteria_sql .= "$key $criteria[0] ($crit_temp)";
} else {
$criteria_sql .= "$key $criteria[0] (?) ";
$criteria_data[] = $criteria[1];
} }
} else {
$criteria_sql = "WHERE {$criterias[0]} = ? ";
$criteria_data[] = $criterias[1];
} }
} }
foreach ($select as $value) { foreach ($select as $value) {
$select_sql .= $value . ', '; $select_sql .= $value . ', ';
} }
@@ -335,47 +424,60 @@ abstract class Entity {
} }
$results = DBInstance::query($sql, $criteria_data, static::_connectionName); $results = DBInstance::query($sql, $criteria_data, static::_connectionName);
$objects = Array(); $objects = new Collection();
foreach ($results as $value) { foreach ($results as $value) {
$class = static::class; $class = static::class;
$object = new $class; $object = new $class;
$object->fill($value); $object->fill($value);
$objects[] = $object; $objects->addItem($object);
} }
if (empty($objects)) { if (empty($objects)) {
//return false; //new $this->classname; return false; //new $this->classname;
$className = static::class;
return new $className;
} }
return $objects[0]; return $objects[0];
} }
/** /**
* Find Many * Find Many
* *
* @param Array $criterias Description * @param array $criterias Description
* @param Array $select Description * @param array $select Description
* @param Array $limits Description * @param array $limits Description
* @param boolean $trashed Description * @param boolean $trashed Description
* *
*/ */
public static function findMany($criterias = Array(), $select = Array('*'), $limits = Array(), $trashed = false) { public static function findMany(
$select_sql = ""; $criterias = array(),
$criteria_sql = ""; $select = array('*'),
$limits_sql = ""; $limits = array(),
$trashed = false
) {
$select_sql = $criteria_sql = $limits_sql = "";
foreach ($limits as $key => $value) { foreach ($limits as $key => $value) {
$limits_sql .= "$key $value "; $limits_sql .= "$key $value ";
} }
foreach ($criterias as $key => $criteria) { foreach ($criterias as $key => $criteria) {
if ($criteria_sql != "") { if ($criteria_sql != "" && substr($criteria[0], 0, 2) == 'OR') {
$criteria_sql .= " ";
} else if ($criteria_sql != "") {
$criteria_sql .= " ";
} else if ($criteria_sql != "") {
$criteria_sql .= " AND "; $criteria_sql .= " AND ";
} else { } else if ($criteria_sql == "") {
$criteria_sql .= " WHERE "; $criteria_sql .= " WHERE ";
} else {
$criteria_sql .= " ";
} }
if (is_string($criteria[1])) {
if (substr($criteria[0], 0, 2) == "OR") {
$criteria[0] = str_replace('OR', '', $criteria[0]);
$criteria_sql .= "OR $key $criteria[0] ('%$criteria[1]%')";
} else if (is_string($criteria[1])) {
$criteria_sql .= "$key $criteria[0] '$criteria[1]'"; $criteria_sql .= "$key $criteria[0] '$criteria[1]'";
} else if (is_array($criteria[1])) { } else if (is_array($criteria[1])) {
$criteria_sql .= "$key $criteria[0] (" . implode(', ', $criteria[1]) . ")"; $criteria_sql .= "$key $criteria[0] (" . implode(', ', $criteria[1]) . ")";
@@ -384,9 +486,12 @@ abstract class Entity {
} }
} }
$criteria_sql = str_replace('WHERE OR', 'WHERE ', $criteria_sql);
foreach ($select as $value) { foreach ($select as $value) {
$select_sql .= $value . ', '; $select_sql .= $value . ', ';
} }
$select_sql = rtrim($select_sql, ', '); $select_sql = rtrim($select_sql, ', ');
if (static::_softdelete && !$trashed) { if (static::_softdelete && !$trashed) {
@@ -395,23 +500,25 @@ abstract class Entity {
$sql = "SELECT $select_sql FROM {" . static::_tableName . "} $criteria_sql $limits_sql"; $sql = "SELECT $select_sql FROM {" . static::_tableName . "} $criteria_sql $limits_sql";
} }
$results = DBInstance::query($sql, Array(), static::_connectionName); $results = DBInstance::query($sql, array(), static::_connectionName);
$objects = Array(); $objects = new Collection();
foreach ($results as $value) { foreach ($results as $value) {
$class = static::class; $class = static::class;
$object = new $class; $object = new $class;
$object->fill($value); $object->fill($value);
$objects[] = $object; $objects->addItem($object);
} }
if (empty($objects)) { if (empty($objects)) {
return Array(); return array();
} }
return $objects; return $objects;
} }
/** /**
* Has One Local * Has One
* *
* Defines that, this object has a child an only one, * Defines that, this object has a child an only one,
* object in other class. * object in other class.
@@ -422,17 +529,15 @@ abstract class Entity {
* This relation will be created on the User class * This relation will be created on the User class
* making reference to the Phone class * making reference to the Phone class
* *
* @ctag $this->hasOne('foreign_object', 'field_in_remote'); * @param object $foreign_object Class instance from the remote object
*
* @param Object $foreign_object Class instance from the remote object
* @param (int, string) $field_in_remote Field in local object matchin the remote id * @param (int, string) $field_in_remote Field in local object matchin the remote id
* *
* @return Object Instance of the remote class * @return object Instance of the remote class
* *
*/ */
protected function hasOne($foreign_object, $field_in_remote) { protected function hasOne($foreign_object, $field_in_remote)
$obj = new $foreign_object; {
return $obj->findOne(Array($field_in_remote => Array('=', $this->id))); return new HasOne($foreign_object, $field_in_remote, $this);
} }
/** /**
@@ -446,15 +551,13 @@ abstract class Entity {
* This relation will be created on the Post class * This relation will be created on the Post class
* Making reference to the Comment class * Making reference to the Comment class
* *
* @ctag $this->hasMany('foreign_object', 'field_in_foreign'); * @param string $foreignObject Instance of a remote class
* * @param int|string $fieldInForeign The field to match the local id
* @param type $foreign_object Instance of a remote class
* @param (int, string) $field_in_foreign The field to match the local id
* *
*/ */
protected function hasMany($foreign_object, $field_in_foreign) { protected function hasMany(string $foreignObject, int|string $fieldInForeign)
$obj = new $foreign_object; {
return $obj->findMany(Array($field_in_foreign => Array('=', $this->id))); return new HasMany($foreignObject, $fieldInForeign, $this);
} }
/** /**
@@ -469,16 +572,13 @@ abstract class Entity {
* This relation will be created on the comment class * This relation will be created on the comment class
* Making reference to the post class * Making reference to the post class
* *
* @ctag $this->belongsTo('foreign_object', 'local_field'); * @param string $foreignObject Instance of a remote class
* @ctag $this->belongsTo('foreign_object', 'local_field', 'id'); * @param (int, String) $localField Remote field relate to local Object
* * @param string $remoteField
* @param Object $foreign_object Instance of a remote class
* @param (int, String) $local_field Remote field relate to local Object
* @param string $remote_field
*/ */
protected function belongsTo($foreign_object, $local_field, $remote_field = 'id') { protected function belongsTo(string $foreignObject, $localField, $remoteField = 'id')
$obj = new $foreign_object; {
return $obj->findOne(Array($remote_field => Array('=', $this->$local_field))); return new BelongsTo($foreignObject, $localField, $remoteField, $this);
} }
/** /**
@@ -493,35 +593,22 @@ abstract class Entity {
* *
* This relation will be created in both classes * This relation will be created in both classes
* *
* @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot'); * @param Object $foreignObject Instance of the remote class
* @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array()); * @param string $pivotTable Name of the pivot table
* @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array(), $remote_limit = Array()); * @param string $localInPivot Name of field on the pivot in relation of the local class
* * @param int|string $remoteInPivot Name of field on the pivot in relation of the remote class
* @param Object $foreign_object Instance of the remote class * @param Array $remoteFilter Filters to the remote Array('id', Array('>', 50) )
* @param string $pivot_table Name of the pivot table * @param Array $remoteLimit Array( 'offset'=> 10, 'limit' => 10 )
* @param int $local_in_pivot Name of field on the pivot in relation of the local class
* @param int $remote_in_pivot Name of field on the pivot in relation of the remote class
* @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) )
* @param Array $remote_limit Array( 'offset'=> 10, 'limit' => 10 )
*/ */
protected function belongsToMany($foreign_object, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $remote_limit = Array()) { protected function belongsToMany(
$obj = new $foreign_object; string $foreignObject,
$limits_sql = ''; string $pivotTable,
string $localInPivot,
foreach ($remote_limit as $key => $value) { int|string $remoteInPivot,
$limits_sql .= "$key $value "; array $remoteFilter = array(),
} array $remoteLimit = array()
$sql = "SELECT $remote_in_pivot FROM {$pivot_table} WHERE $local_in_pivot = $this->id $limits_sql"; ) {
return new BelongsToMany($this, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter, $remoteLimit);
$relations = DBInstance::query($sql, Array(), static::_connectionName);
$ids = Array();
foreach ($relations as $relation) {
$ids[] = $relation->$remote_in_pivot;
}
if (empty($ids)) {
return Array();
}
return $obj->findMany(array_merge(Array('id' => Array('IN', $ids)), $remote_filter), Array('*'), $remote_limit);
} }
/** /**
@@ -535,41 +622,59 @@ abstract class Entity {
* Table Tag = (id, name) * Table Tag = (id, name)
* Table Post_Tag = (id, postid, tagid) * Table Post_Tag = (id, postid, tagid)
* *
* @ctag $this->belongsToManyExtended('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot');
* @ctag $this->belongsToManyExtended('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array());
* @ctag $this->belongsToManyExtended('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array(), $pivot_limits = Array());
*
* This relation will be created in both classes * This relation will be created in both classes
* *
* @param Object $foreign_object Instance of the remote class * @param Object $foreignObject Instance of the remote class
* @param string $pivot_table Name of the pivot table * @param String $pivotTable Name of the pivot table
* @param int $local_in_pivot Name of field on the pivot in relation of the local class * @param String $localInPivot Name of field on the pivot in relation of the local class
* @param int $remote_in_pivot Name of field on the pivot in relation of the remote class * @param String $remoteInPivot Name of field on the pivot in relation of the remote class
* @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) ) * @param Array $remoteFilter Filters to the remote Array('id', Array('>', 50) )
* @param Array $pivot_limits Array( 'offset'=> 10, 'limit' => 10 ) * @param Array $pivotLimit Array( 'offset'=> 10, 'limit' => 10 )
* @param bool $softDelete
*/ */
protected function belongsToManyExtended($foreign_object, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $pivot_limits = Array()) { protected function belongsToManyExtended(
$obj = new $foreign_object; string $foreignObject,
$limits_sql = ''; string $pivotTable,
foreach ($pivot_limits as $key => $value) { string $localInPivot,
$limits_sql .= "$key $value "; string $remoteInPivot,
} array $remoteFilter = array(),
array $pivotLimit = array(),
$sql = "SELECT * FROM $pivot_table WHERE $local_in_pivot = $this->id $limits_sql"; $softDelete = true
$relations = DBInstance::query($sql, Array(), static::_connectionName); ) {
$objects = Array(); return new BelongsToManyExtended($this, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter, $pivotLimit, $softDelete);
if (empty($relations)) {
return Array();
}
foreach ($relations as $relation) {
$relation->child_element = $obj->findOne(array_merge(Array("id" => Array("=", $relation->$remote_in_pivot)), $remote_filter));
$objects[] = $relation;
}
if (empty($objects)) {
return Array();
}
return $objects;
} }
/**
* Eager load relations on this entity
*
* @param null|array|string $relations
* @param null|array|string $propagate
*
* @return Entity
*/
public function with(
null|array|string $relations = null,
null|array|string $propagate = null
) {
if (!$relations) {
return $this;
}
if (is_string($relations)) {
$relations = [$relations];
}
$possibleRelations = get_class_methods(static::class);
foreach ($relations as $relation) {
if (in_array($relation, $possibleRelations)) {
$this->$relation = $this->$relation()->get();
}
if ($this->$relation && $propagate) {
$this->$relation->with($propagate);
}
}
return $this;
}
} }
-21
View File
@@ -1,21 +0,0 @@
<?php
namespace ORM;
class HasMany {
private $foreignObject;
private $remoteField;
private $localElement;
function __construct($foreignObject, $remoteField, $localElement) {
$this->foreignObject = $foreignObject;
$this->remoteField = $remoteField;
$this->localElement = $localElement;
}
function get() {
return $this->foreignObject::findMany(Array($this->remoteField => Array('=', $this->localElement->id)));
}
}
-22
View File
@@ -1,22 +0,0 @@
<?php
namespace ORM
;
class HasOne{
private $foreignObject;
private $remoteField;
private $localElement;
function __construct($foreignObject, $remoteField, $localElement) {
$this->foreignObject = $foreignObject;
$this->remoteField = $remoteField;
$this->localElement = $localElement;
}
function get(){
return $this->foreignObject::findOne(Array($this->remoteField => Array('=', $this->localElement->id)));
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace ORM\Relations;
/**
* BelongsTo
*
* Defines that, this object is part of an other class.
* The local field must match the id of an other class.
*
* Table Post = (id, name, content)
* Table Comment = (id, name, content, postid)
*
* This relation will be created on the comment class
* Making reference to the post class
*/
class BelongsTo {
private $foreignObject;
private $localField;
private $remoteField;
private $localElement;
function __construct($foreignObject, $localField, $remoteField = 'id', $localElement) {
$this->foreignObject = $foreignObject;
$this->localField = $localField;
$this->remoteField = $remoteField;
$this->localElement = $localElement;
}
public function __call($name, $arguments)
{
return $this->get()->$name($arguments);
}
public function __get($key)
{
return $this->get()->$key;
}
function get() {
return $this->foreignObject::findOne(Array($this->remoteField => Array('=', $this->localElement->{$this->localField})));
}
}
@@ -1,7 +1,22 @@
<?php <?php
namespace ORM; namespace ORM\Relations;
use ORM\DBInstance;
use ORM\Collection;
/**
* Belongs to Many
*
* Defines that this object is related to many other instances
* of other classes throw a pivot table.
*
* Table Post = (id, name, content)
* Table Tag = (id, name)
* Table Post_Tag = (id, postid, tagid)
*
* This relation will be created in both classes
*/
class BelongsToMany { class BelongsToMany {
private $localObject; private $localObject;
@@ -12,6 +27,17 @@ class BelongsToMany {
private $remoteFilter; private $remoteFilter;
private $remoteLimit; private $remoteLimit;
/**
* Build the Connection
*
* @param mixed $localObject
* @param mixed $foreignObject
* @param mixed $pivotTable
* @param mixed $localInPivot
* @param mixed $remoteInPivot
* @param mixed $remoteFilter
* @param mixed $remoteLimit
*/
function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array()) { function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array()) {
$this->localObject = $localObject; $this->localObject = $localObject;
$this->foreignObject = $foreignObject; $this->foreignObject = $foreignObject;
@@ -22,7 +48,7 @@ class BelongsToMany {
$this->remoteLimit = $remoteLimit; $this->remoteLimit = $remoteLimit;
} }
function get() { function get() : Collection {
$limitsSql = ''; $limitsSql = '';
foreach ($this->remoteLimit as $key => $value) { foreach ($this->remoteLimit as $key => $value) {
@@ -40,7 +66,7 @@ class BelongsToMany {
} }
if (empty($ids)) { if (empty($ids)) {
return Array(); return new Collection();
} }
return $this->foreignObject::findMany(array_merge(Array('id' => Array('IN', $ids)), $this->remoteFilter), Array('*'), $this->remoteLimit); return $this->foreignObject::findMany(array_merge(Array('id' => Array('IN', $ids)), $this->remoteFilter), Array('*'), $this->remoteLimit);
@@ -1,6 +1,9 @@
<?php <?php
namespace ORM; namespace ORM\Relations;
use ORM\DBInstance;
use ORM\Collection;
class BelongsToManyExtended { class BelongsToManyExtended {
@@ -11,8 +14,9 @@ class BelongsToManyExtended {
private $remoteInPivot; private $remoteInPivot;
private $remoteFilter; private $remoteFilter;
private $remoteLimit; private $remoteLimit;
private $softDelete;
function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array()) { function __construct($localObject, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter = Array(), $remoteLimit = Array(), $softDelete) {
$this->localObject = $localObject; $this->localObject = $localObject;
$this->foreignObject = $foreignObject; $this->foreignObject = $foreignObject;
$this->pivotTable = $pivotTable; $this->pivotTable = $pivotTable;
@@ -20,23 +24,31 @@ class BelongsToManyExtended {
$this->remoteInPivot = $remoteInPivot; $this->remoteInPivot = $remoteInPivot;
$this->remoteFilter = $remoteFilter; $this->remoteFilter = $remoteFilter;
$this->remoteLimit = $remoteLimit; $this->remoteLimit = $remoteLimit;
$this->softDelete = $softDelete;
} }
function get(){ function get() : Collection {
$limitsSql = ''; $limitsSql = '';
foreach ($this->remoteLimit as $key => $value) { foreach ($this->remoteLimit as $key => $value) {
$limitsSql .= "$key $value "; $limitsSql .= "$key $value ";
} }
$pivotTable = '{' . $this->pivotTable . '}'; $pivotTable = '{' . $this->pivotTable . '}';
$sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
$sql = '';
if($this->softDelete){
$sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? AND deleted_at IS NULL $limitsSql";
} else {
$sql = "SELECT * FROM $pivotTable WHERE $this->localInPivot = ? $limitsSql";
}
$relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName); $relations = DBInstance::query($sql, Array($this->localObject->id), $this->localObject::_connectionName);
$objects = Array(); $objects = new Collection();
if (empty($relations)) { if (empty($relations)) {
return Array(); return new Collection();
} }
foreach ($relations as $relation) { foreach ($relations as $relation) {
@@ -45,8 +57,9 @@ class BelongsToManyExtended {
} }
if (empty($objects)) { if (empty($objects)) {
return Array(); return new Collection();
} }
return $objects; return $objects;
} }
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace ORM\Relations;
/**
* HasMany
*
* Defines that, this object has many instances of other Object
*
* Table Post = (id, name, content)
* Table Comment = (id, name, content, postid)
*
* This relation will be created on the Post class
* Making reference to the Comment class
*/
class HasMany
{
private $foreignObject;
private $remoteField;
private $localElement;
/**
* Return the Relation
*
* @param mixed $foreignObject
* @param mixed $remoteField
* @param mixed $localElement
*/
function __construct($foreignObject, $remoteField, $localElement)
{
$this->foreignObject = $foreignObject;
$this->remoteField = $remoteField;
$this->localElement = $localElement;
}
/**
* Get the data of the relation
*/
function get()
{
return $this->foreignObject::findMany(array($this->remoteField => array('=', $this->localElement->id)));
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace ORM\Relations;
/**
* Has One
*
* Defines that, this object has a child only one object in other class.
*
* Table user = (id, name)
* Table phone = (id, number, userid)
*
* This relation will be created on the User class
* making reference to the Phone class
*/
class HasOne
{
private $foreignObject;
private $remoteField;
private $localElement;
function __construct($foreignObject, $remoteField, $localElement)
{
$this->foreignObject = $foreignObject;
$this->remoteField = $remoteField;
$this->localElement = $localElement;
}
function get()
{
return $this->foreignObject::findOne(array($this->remoteField => array('=', $this->localElement->id)));
}
}