Compare commits
6
Commits
c2f00d6c21
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2084c161d | ||
|
|
29d05b84e6 | ||
|
|
46dd177be9 | ||
|
|
64bce1da47 | ||
|
|
ac04cd02f4 | ||
|
|
bd2f3bddff |
@@ -1,3 +1,215 @@
|
||||
# ORM
|
||||
aasasf
|
||||
ddd
|
||||
# urfat-orm
|
||||
|
||||
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
|
||||
|
||||
+66
-18
@@ -3,29 +3,72 @@
|
||||
namespace ORM;
|
||||
|
||||
/**
|
||||
* \PDO generator class
|
||||
*
|
||||
* This code is based on the TConnection.php class on the Adianti Framework
|
||||
*
|
||||
* @license http://www.adianti.com.br/framework-license
|
||||
*
|
||||
*/
|
||||
* \PDO generator class
|
||||
*
|
||||
* This code is based on the TConnection.php class on the Adianti Framework
|
||||
*
|
||||
* @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;
|
||||
$name = isset($connection_info['name']) ? $connection_info['name'] : NULL;
|
||||
$host = isset($connection_info['host']) ? $connection_info['host'] : NULL;
|
||||
$driver = isset($connection_info['driver']) ? $connection_info['driver'] : NULL;
|
||||
$port = isset($connection_info['port']) ? $connection_info['port'] : NULL;
|
||||
$prefix = isset($connection_info['prefix']) ? $connection_info['prefix'] : '';
|
||||
/**
|
||||
* Open a new connection
|
||||
*
|
||||
* You need to pass a connection configuration in a Object/Array
|
||||
*
|
||||
* user
|
||||
* 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) {
|
||||
case 'pgsql':
|
||||
@@ -49,8 +92,13 @@ class Connection {
|
||||
$conn = new \PDO("mssql:host={$host},1433;dbname={$name}", $user, $pass);
|
||||
break;
|
||||
}
|
||||
|
||||
$conn->prefix = $prefix;
|
||||
$conn->driver = $driver;
|
||||
$conn->traceSQL = $traceSQL;
|
||||
|
||||
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
return $conn;
|
||||
}
|
||||
|
||||
|
||||
+18
-27
@@ -38,7 +38,7 @@ class DBInstance
|
||||
* @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(string $sql, Array $data = null, string $instance = 'default')
|
||||
public static function execute(string $sql, Array $data = Array(), string $instance = 'default')
|
||||
{
|
||||
$sql = self::addPrefix($sql, $instance);
|
||||
if ($data) {
|
||||
@@ -65,16 +65,13 @@ class DBInstance
|
||||
*
|
||||
* This method will execute a SQL and return a pointer to the resultset
|
||||
*
|
||||
* @ctag DBInstance::query($sql);
|
||||
* @ctag DBInstance::query($sql, []);
|
||||
*
|
||||
* @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
|
||||
*
|
||||
* @return mixed 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);
|
||||
|
||||
@@ -85,7 +82,7 @@ class DBInstance
|
||||
$con = Connections::getConnection($instance);
|
||||
return $con->query($sql, \PDO::FETCH_OBJ);
|
||||
} catch (\Throwable $th) {
|
||||
ddd($sql);
|
||||
var_dump($th); die;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,9 +90,6 @@ class DBInstance
|
||||
/**
|
||||
* queryOne
|
||||
*
|
||||
* @ctag DBInstance::queryOne($sql);
|
||||
* @ctag DBInstance::queryOne($sql, []);
|
||||
*
|
||||
* This method will execute a SQL and return the first featched register
|
||||
*
|
||||
* @param string $sql The SQL to be executed
|
||||
@@ -122,10 +116,6 @@ class DBInstance
|
||||
*
|
||||
* This method will execute get a register from a table
|
||||
*
|
||||
* @ctag DBInstance::getRecord($table);
|
||||
* @ctag DBInstance::getRecord($table, []);
|
||||
* @ctag DBInstance::getRecord($table, [], []);
|
||||
*
|
||||
* @param string $table The table to be searched
|
||||
* @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
|
||||
@@ -174,9 +164,6 @@ class DBInstance
|
||||
*
|
||||
* This method will get a record from the database using SQL
|
||||
*
|
||||
* @ctag DBInstance::getRecordSql($sql);
|
||||
* @ctag DBInstance::getRecordSql($sql, []);
|
||||
*
|
||||
* @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
|
||||
@@ -200,9 +187,6 @@ class DBInstance
|
||||
*
|
||||
* This method will get records from the database
|
||||
*
|
||||
* @ctag DBInstance::getRecords($table);
|
||||
* @ctag DBInstance::getRecords($table, []);
|
||||
*
|
||||
* @param string $table The table to be searched
|
||||
* @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
|
||||
@@ -212,6 +196,11 @@ class DBInstance
|
||||
*/
|
||||
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);
|
||||
|
||||
$elements = array();
|
||||
@@ -227,9 +216,6 @@ class DBInstance
|
||||
*
|
||||
* This method will get records from the database
|
||||
*
|
||||
* @ctag DBInstance::getRecordsPointer($table);
|
||||
* @ctag DBInstance::getRecordsPointer($table, []);
|
||||
*
|
||||
* @param string $table The table to be searched
|
||||
* @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
|
||||
@@ -284,9 +270,6 @@ class DBInstance
|
||||
*
|
||||
* This method will get records from the database
|
||||
*
|
||||
* @ctag DBInstance::getRecordsSql($sql);
|
||||
* @ctag DBInstance::getRecordsSql($sql, []);
|
||||
*
|
||||
* @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
|
||||
@@ -317,7 +300,8 @@ class DBInstance
|
||||
* @param string $table
|
||||
* @param array $data
|
||||
* @param string $connection
|
||||
* @return void
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function insertRecord($table, $data = array(), $connection = 'default')
|
||||
{
|
||||
@@ -345,6 +329,8 @@ class DBInstance
|
||||
$sql = "INSERT INTO {" . $table . "} ($first_argument) VALUES ($second_argument)";
|
||||
|
||||
DBInstance::execute($sql, $insert_data, $connection);
|
||||
|
||||
return self::lastInsert($connection);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -359,11 +345,16 @@ class DBInstance
|
||||
try {
|
||||
$sql = self::addPrefix($sql, $instance);
|
||||
$con = Connections::getConnection($instance);
|
||||
|
||||
if($con->traceSQL){
|
||||
echo "$sql \n";
|
||||
}
|
||||
|
||||
$statement = $con->prepare($sql);
|
||||
$statement->execute($data);
|
||||
return $statement->fetchAll(\PDO::FETCH_OBJ);
|
||||
} catch (\Throwable $th) {
|
||||
error_log('adsdsadsadsa');
|
||||
error_log($th);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+167
-124
@@ -2,12 +2,19 @@
|
||||
|
||||
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 _connectionName = 'default';
|
||||
const _softdelete = false;
|
||||
const _ignore = Array(
|
||||
const _ignore = array(
|
||||
'classname',
|
||||
'_properties',
|
||||
'_ignore',
|
||||
@@ -18,7 +25,7 @@ abstract class Entity {
|
||||
'_idPolice',
|
||||
'_ignore'
|
||||
);
|
||||
const _properties = Array();
|
||||
const _properties = array();
|
||||
|
||||
/*
|
||||
* [type] = nextval| manual | empty is the default
|
||||
@@ -26,9 +33,10 @@ abstract class Entity {
|
||||
* [min] = minumul value allowed
|
||||
* [step] = increment by n each id
|
||||
*/
|
||||
const _idPolice = Array();
|
||||
const _idPolice = array();
|
||||
|
||||
function __construct($assignment = '') {
|
||||
function __construct($assignment = '')
|
||||
{
|
||||
|
||||
@$this->_ignore = array_merge((array) $this->_ignore, self::_ignore);
|
||||
|
||||
@@ -38,21 +46,23 @@ abstract class Entity {
|
||||
}
|
||||
|
||||
// Mass Assign
|
||||
if(is_array($assignment)){
|
||||
if (is_array($assignment)) {
|
||||
$this->charge($assignment);
|
||||
}
|
||||
}
|
||||
|
||||
public function __set($property, $value) {
|
||||
public function __set($property, $value)
|
||||
{
|
||||
if (in_array($property, static::_ignore)) {
|
||||
return;
|
||||
}
|
||||
$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)){
|
||||
if (method_exists($this, $key)) {
|
||||
return $this->$key();
|
||||
}
|
||||
|
||||
@@ -65,7 +75,8 @@ abstract class Entity {
|
||||
return $this->$key;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
public function __toString()
|
||||
{
|
||||
if (isset($this->name)) {
|
||||
return $this->name;
|
||||
}
|
||||
@@ -75,16 +86,15 @@ abstract class Entity {
|
||||
return static::class;
|
||||
}
|
||||
|
||||
/*public function __call($name, $arguments){
|
||||
dd($name);
|
||||
}*/
|
||||
// public function __call($name, $arguments){ }
|
||||
|
||||
public function charge($payload) {
|
||||
public function charge($payload)
|
||||
{
|
||||
|
||||
$properties = [];
|
||||
|
||||
foreach( get_object_vars($this) as $key => $property){
|
||||
if(substr($key, 0, 1) != '_'){
|
||||
foreach (get_object_vars($this) as $key => $property) {
|
||||
if (substr($key, 0, 1) != '_') {
|
||||
$properties[] = $key;
|
||||
}
|
||||
}
|
||||
@@ -95,7 +105,7 @@ abstract class Entity {
|
||||
if ($property == 'id' && !isset($payload[$property])) {
|
||||
continue;
|
||||
}
|
||||
if(empty($payload[$property])){
|
||||
if (empty($payload[$property])) {
|
||||
continue;
|
||||
}
|
||||
$this->$property = $payload[$property];
|
||||
@@ -103,8 +113,9 @@ abstract class Entity {
|
||||
return [];
|
||||
}
|
||||
|
||||
public static function get_properties() {
|
||||
$properties = Array();
|
||||
public static function get_properties()
|
||||
{
|
||||
$properties = array();
|
||||
foreach (static::_properties as $propertie) {
|
||||
$obj = new \stdClass();
|
||||
$obj->data = $propertie;
|
||||
@@ -113,7 +124,8 @@ abstract class Entity {
|
||||
return json_encode($properties);
|
||||
}
|
||||
|
||||
public function save() {
|
||||
public function save()
|
||||
{
|
||||
if (isset($this->id)) {
|
||||
$this->update();
|
||||
} else {
|
||||
@@ -121,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
|
||||
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();
|
||||
return;
|
||||
}
|
||||
@@ -134,7 +147,7 @@ abstract class Entity {
|
||||
$obj = (array) $this;
|
||||
|
||||
$update_string = '';
|
||||
$update_data = Array();
|
||||
$update_data = array();
|
||||
$update_data['_update_id'] = $this->id;
|
||||
|
||||
if (isset($this->_timestamps) && $this->_timestamps) {
|
||||
@@ -152,7 +165,8 @@ abstract class Entity {
|
||||
DBInstance::execute($sql, $update_data, static::_connectionName);
|
||||
}
|
||||
|
||||
private function create() {
|
||||
private function create()
|
||||
{
|
||||
//First, let's verify id polices
|
||||
//Manual and empty don't need special treatments
|
||||
if (!empty(static::_idPolice) && static::_idPolice['type'] != 'manual') {
|
||||
@@ -185,7 +199,7 @@ abstract class Entity {
|
||||
|
||||
$first_argument = '';
|
||||
$second_argument = '';
|
||||
$insert_data = Array();
|
||||
$insert_data = array();
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$first_argument .= $column . ', ';
|
||||
@@ -207,40 +221,45 @@ abstract class Entity {
|
||||
}
|
||||
|
||||
|
||||
public function load($id = false) {
|
||||
public function load($id = false)
|
||||
{
|
||||
if (!$id) {
|
||||
return;
|
||||
}
|
||||
|
||||
$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 delete() {
|
||||
public function delete()
|
||||
{
|
||||
if (static::_softdelete) {
|
||||
$this->deleted_at = date('Y-m-d h:m:s');
|
||||
$this->update();
|
||||
}else{
|
||||
} else {
|
||||
$this->purge();
|
||||
}
|
||||
}
|
||||
|
||||
public function purge() {
|
||||
public function purge()
|
||||
{
|
||||
$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);
|
||||
}
|
||||
|
||||
public function restore(){
|
||||
public function restore()
|
||||
{
|
||||
if (isset($this->_softdelete) && $this->_softdelete) {
|
||||
$this->deleted_at = null;
|
||||
$this->update();
|
||||
}else{
|
||||
} else {
|
||||
throw new \Exception('Not soft deleteble');
|
||||
}
|
||||
}
|
||||
|
||||
private function fill($data) {
|
||||
private function fill($data)
|
||||
{
|
||||
$data = (array) $data;
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
@@ -258,7 +277,8 @@ abstract class Entity {
|
||||
* @param Array $limits Array( 'offset'=> 10, 'limit' => 10 )
|
||||
* @param boolean $trashed Bring trashed elements?
|
||||
*/
|
||||
public static function findAll($select = Array('*'), $limits = Array(), $trashed = false) : Collection {
|
||||
public static function findAll($select = array('*'), $limits = array(), $trashed = false): Collection
|
||||
{
|
||||
$criteria = '';
|
||||
$limits_sql = '';
|
||||
|
||||
@@ -278,7 +298,7 @@ abstract class Entity {
|
||||
$sql = "SELECT $criteria FROM {" . static::_tableName . "} $limits_sql";
|
||||
}
|
||||
|
||||
$results = DBInstance::query($sql, Array(), static::_connectionName);
|
||||
$results = DBInstance::query($sql, array(), static::_connectionName);
|
||||
$objects = new Collection;
|
||||
|
||||
foreach ($results as $value) {
|
||||
@@ -300,9 +320,10 @@ abstract class Entity {
|
||||
* @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_data = Array();
|
||||
$criteria_data = array();
|
||||
foreach ($criterias as $key => $criteria) {
|
||||
if ($criteria_sql != "") {
|
||||
$criteria_sql .= " AND ";
|
||||
@@ -335,48 +356,58 @@ abstract class Entity {
|
||||
/**
|
||||
* 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 Boolan $trashed true, false
|
||||
* @param bool $trashed true, false
|
||||
*/
|
||||
public static function findOne($criterias = Array(), $select = Array('*'), $trashed = false) {
|
||||
if(empty($criterias)){
|
||||
$criterias = Array(1 => ['=', 1]);
|
||||
public static function findOne(
|
||||
int|string|array $criterias = array(),
|
||||
array $select = array('*'),
|
||||
bool $trashed = false
|
||||
) {
|
||||
if (empty($criterias)) {
|
||||
$criterias = array(1 => ['=', 1]);
|
||||
}
|
||||
|
||||
$select_sql = "";
|
||||
$criteria_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_data[] = $criterias;
|
||||
} else {
|
||||
foreach ($criterias as $key => $criteria) {
|
||||
if ($criteria_sql != "") {
|
||||
$criteria_sql .= " AND ";
|
||||
} else if ($criteria_sql == "") {
|
||||
$criteria_sql .= " WHERE ";
|
||||
} else {
|
||||
$criteria_sql .= " ";
|
||||
}
|
||||
if (is_array($criteria[1])) {
|
||||
$crit_temp = '';
|
||||
foreach ($criteria[1] as $crit) {
|
||||
$crit_temp .= '?, ';
|
||||
$criteria_data[] = $crit;
|
||||
if (!array_is_list($criterias)) {
|
||||
foreach ($criterias as $key => $criteria) {
|
||||
if ($criteria_sql != "") {
|
||||
$criteria_sql .= " AND ";
|
||||
} else if ($criteria_sql == "") {
|
||||
$criteria_sql .= " WHERE ";
|
||||
} else {
|
||||
$criteria_sql .= " ";
|
||||
}
|
||||
if (is_array($criteria[1])) {
|
||||
$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) {
|
||||
$select_sql .= $value . ', ';
|
||||
}
|
||||
@@ -418,10 +449,13 @@ abstract class Entity {
|
||||
* @param boolean $trashed Description
|
||||
*
|
||||
*/
|
||||
public static function findMany($criterias = Array(), $select = Array('*'), $limits = Array(), $trashed = false) {
|
||||
$select_sql = "";
|
||||
$criteria_sql = "";
|
||||
$limits_sql = "";
|
||||
public static function findMany(
|
||||
$criterias = array(),
|
||||
$select = array('*'),
|
||||
$limits = array(),
|
||||
$trashed = false
|
||||
) {
|
||||
$select_sql = $criteria_sql = $limits_sql = "";
|
||||
|
||||
foreach ($limits as $key => $value) {
|
||||
$limits_sql .= "$key $value ";
|
||||
@@ -430,9 +464,9 @@ abstract class Entity {
|
||||
foreach ($criterias as $key => $criteria) {
|
||||
if ($criteria_sql != "" && substr($criteria[0], 0, 2) == 'OR') {
|
||||
$criteria_sql .= " ";
|
||||
} else if ($criteria_sql != "" ) {
|
||||
} else if ($criteria_sql != "") {
|
||||
$criteria_sql .= " ";
|
||||
} else if ($criteria_sql != "" ) {
|
||||
} else if ($criteria_sql != "") {
|
||||
$criteria_sql .= " AND ";
|
||||
} else if ($criteria_sql == "") {
|
||||
$criteria_sql .= " WHERE ";
|
||||
@@ -466,7 +500,7 @@ abstract class Entity {
|
||||
$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 = new Collection();
|
||||
|
||||
foreach ($results as $value) {
|
||||
@@ -477,14 +511,14 @@ abstract class Entity {
|
||||
}
|
||||
|
||||
if (empty($objects)) {
|
||||
return Array();
|
||||
return array();
|
||||
}
|
||||
|
||||
return $objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Has One Local
|
||||
* Has One
|
||||
*
|
||||
* Defines that, this object has a child an only one,
|
||||
* object in other class.
|
||||
@@ -495,15 +529,14 @@ abstract class Entity {
|
||||
* This relation will be created on the User 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 (int, string) $field_in_remote Field in local object matchin the remote id
|
||||
*
|
||||
* @return object Instance of the remote class
|
||||
*
|
||||
*/
|
||||
protected function hasOne($foreign_object, $field_in_remote) {
|
||||
protected function hasOne($foreign_object, $field_in_remote)
|
||||
{
|
||||
return new HasOne($foreign_object, $field_in_remote, $this);
|
||||
}
|
||||
|
||||
@@ -518,14 +551,13 @@ abstract class Entity {
|
||||
* This relation will be created on the Post class
|
||||
* Making reference to the Comment class
|
||||
*
|
||||
* @ctag $this->hasMany('foreign_object', 'field_in_foreign');
|
||||
*
|
||||
* @param Entity $foreign_object Instance of a remote class
|
||||
* @param (int, string) $field_in_foreign The field to match the local id
|
||||
* @param string $foreignObject Instance of a remote class
|
||||
* @param int|string $fieldInForeign The field to match the local id
|
||||
*
|
||||
*/
|
||||
protected function hasMany($foreign_object, $field_in_foreign) {
|
||||
return new HasMany($foreign_object, $field_in_foreign, $this);
|
||||
protected function hasMany(string $foreignObject, int|string $fieldInForeign)
|
||||
{
|
||||
return new HasMany($foreignObject, $fieldInForeign, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -540,14 +572,12 @@ abstract class Entity {
|
||||
* This relation will be created on the comment class
|
||||
* Making reference to the post class
|
||||
*
|
||||
* @ctag $this->belongsTo('foreign_object', 'local_field');
|
||||
* @ctag $this->belongsTo('foreign_object', 'local_field', 'id');
|
||||
*
|
||||
* @param Entity $foreign_object Instance of a remote class
|
||||
* @param (int, String) $local_field Remote field relate to local Object
|
||||
* @param string $remote_field
|
||||
* @param string $foreignObject Instance of a remote class
|
||||
* @param (int, String) $localField Remote field relate to local Object
|
||||
* @param string $remoteField
|
||||
*/
|
||||
protected function belongsTo($foreignObject, $localField, $remoteField = 'id') {
|
||||
protected function belongsTo(string $foreignObject, $localField, $remoteField = 'id')
|
||||
{
|
||||
return new BelongsTo($foreignObject, $localField, $remoteField, $this);
|
||||
}
|
||||
|
||||
@@ -563,19 +593,22 @@ abstract class Entity {
|
||||
*
|
||||
* This relation will be created in both classes
|
||||
*
|
||||
* @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot');
|
||||
* @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array());
|
||||
* @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array(), $remote_limit = Array());
|
||||
*
|
||||
* @param Object $foreign_object Instance of the remote class
|
||||
* @param string $pivot_table Name of the pivot table
|
||||
* @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 )
|
||||
* @param Object $foreignObject Instance of the remote class
|
||||
* @param string $pivotTable Name of the pivot table
|
||||
* @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 Array $remoteFilter Filters to the remote Array('id', Array('>', 50) )
|
||||
* @param Array $remoteLimit Array( 'offset'=> 10, 'limit' => 10 )
|
||||
*/
|
||||
protected function belongsToMany($foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $remote_limit = Array()) {
|
||||
return new BelongsToMany($this, $foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter, $remote_limit);
|
||||
protected function belongsToMany(
|
||||
string $foreignObject,
|
||||
string $pivotTable,
|
||||
string $localInPivot,
|
||||
int|string $remoteInPivot,
|
||||
array $remoteFilter = array(),
|
||||
array $remoteLimit = array()
|
||||
) {
|
||||
return new BelongsToMany($this, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter, $remoteLimit);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -589,45 +622,55 @@ abstract class Entity {
|
||||
* Table Tag = (id, name)
|
||||
* 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
|
||||
*
|
||||
* @param Object $foreign_object Instance of the remote class
|
||||
* @param string $pivot_table Name of the pivot table
|
||||
* @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 $pivot_limits Array( 'offset'=> 10, 'limit' => 10 )
|
||||
* @param Object $foreignObject Instance of the remote class
|
||||
* @param String $pivotTable Name of the pivot table
|
||||
* @param String $localInPivot Name of field on the pivot in relation of the local class
|
||||
* @param String $remoteInPivot Name of field on the pivot in relation of the remote class
|
||||
* @param Array $remoteFilter Filters to the remote Array('id', Array('>', 50) )
|
||||
* @param Array $pivotLimit Array( 'offset'=> 10, 'limit' => 10 )
|
||||
* @param bool $softDelete
|
||||
*/
|
||||
protected function belongsToManyExtended($foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $pivot_limit = Array(), $softDelete = true) {
|
||||
return new BelongsToManyExtended($this, $foreignObject, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter, $pivot_limit, $softDelete);
|
||||
protected function belongsToManyExtended(
|
||||
string $foreignObject,
|
||||
string $pivotTable,
|
||||
string $localInPivot,
|
||||
string $remoteInPivot,
|
||||
array $remoteFilter = array(),
|
||||
array $pivotLimit = array(),
|
||||
$softDelete = true
|
||||
) {
|
||||
return new BelongsToManyExtended($this, $foreignObject, $pivotTable, $localInPivot, $remoteInPivot, $remoteFilter, $pivotLimit, $softDelete);
|
||||
}
|
||||
|
||||
/**
|
||||
* With
|
||||
*
|
||||
* Eager load relations on this entity
|
||||
*
|
||||
**/
|
||||
public function with($relations = null, $propagate = null){
|
||||
if(is_string($relations)){
|
||||
$relations = [$relations];
|
||||
* @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(!$relations){
|
||||
return $this;
|
||||
if (is_string($relations)) {
|
||||
$relations = [$relations];
|
||||
}
|
||||
|
||||
$possibleRelations = get_class_methods(static::class);
|
||||
|
||||
foreach($relations as $relation){
|
||||
if(in_array($relation, $possibleRelations)){
|
||||
foreach ($relations as $relation) {
|
||||
if (in_array($relation, $possibleRelations)) {
|
||||
$this->$relation = $this->$relation()->get();
|
||||
}
|
||||
if($this->$relation){
|
||||
if ($this->$relation && $propagate) {
|
||||
$this->$relation->with($propagate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace ORM;
|
||||
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;
|
||||
@@ -1,7 +1,22 @@
|
||||
<?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 {
|
||||
|
||||
private $localObject;
|
||||
@@ -12,6 +27,17 @@ class BelongsToMany {
|
||||
private $remoteFilter;
|
||||
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()) {
|
||||
$this->localObject = $localObject;
|
||||
$this->foreignObject = $foreignObject;
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace ORM;
|
||||
namespace ORM\Relations;
|
||||
|
||||
use ORM\DBInstance;
|
||||
use ORM\Collection;
|
||||
|
||||
class BelongsToManyExtended {
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user