2017 © Pedro Peláez
 

library orm

The creatively named object-relational mapping library for csrdelft.nl

image

csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  • Thursday, July 19, 2018
  • by qurben
  • Repository
  • 5 Watchers
  • 2 Stars
  • 134 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 2 Forks
  • 12 Open issues
  • 16 Versions
  • 17 % Grown

The README.md

Maintainability Rating Coverage Build Status, (*1)

C.S.R. Delft ORM

A simple object-relational mapper for PHP. We currently use this library in production on csrdelft.nl., (*2)

Installation

Install with composer, (*3)

composer require csrdelft/orm

Before the ORM can be used the cache and database must be initialized. The memcache needs a unix socket or host and port and the database and database admin need a host, database, username and password. After this any model has access to the database., (*4)

CsrDelft\Orm\Configuration::load([
  'cache_path' => '/path/to/data/dir/cache.socket', // Host or unix socket
  'cache_port' => 11211, // Optional if cache_path is a host
  'db' => [
    'host' => 'localhost',
    'db' => 'myDatabase',
    'user' => 'myUser',
    'pass' => 'myPass'
  ]
]);

Usage

The ORM relies on models and entities. Models are classes which interface with the database. Entities are data classes which contain a definition for the database tables. This document will give a brief overview of the basic things you need to know in order to get started., (*5)

Entity

An entity is an object containing data, like for instance a car, person, etc., (*6)

When you want to save an entity to the database, you'll have to extend the class PersistentEntity. An entity must contain a few variables, which are discussed below. An entity must only contain logic about itself, not logic about other classes or about other instances of the same entity. This should be in the Model (or the controller which is not part of this library)., (*7)

Entities are placed in the folder model/entity/ and are named EntityName.php., (*8)

Variables in an entity

For each attribute of an entity there must be a public variable. These will be used by the model when loading from a database., (*9)

public $id;
public $num_wheels;
public $color;
$table_name

The name of the table in the database., (*10)

protected static $table_name = 'cars';
$persistent_attributes

An array of attributes of the entity, mapped to a type., (*11)

A Type is an array, with the following values., (*12)

  • 0: Type from T (PersistentAttributeType.enum)
  • 1: Is this variable nullable?
  • 2: If 0 is T::Enumeration, the enum class (extends PersistentEnum). Else 'extra', for instance auto_increment or comment.
protected static $persistent_attributes = [
  'id' => [T::Integer, false, 'auto_increment'],
  'num_wheels' => [T::Integer],
  'color' => [T::Enumeration, false, 'ColorEnum']
];
$primary_key

An array with the full primary key., (*13)

protected static $primary_key = ['id'];
$computed_attributes

An array of computed attributes. This maps these attributes to a function and adds them to jsonSerialize, (*14)

protected static $computed_attributes = [
  'my_val' => [T::Integer],
];

protected function getMyVal() {
  return 42;
}

Example

model/entities/Car.php, (*15)

class Car extends PersistentEntity {
  public $id;
  public $num_wheels;
  public $color;

  public function carType() {
    if ($this->num_wheels == 4) {
      return "Normal car";
    } else {
      return "Weird car";
    }
  }

  protected static $table_name = 'cars';
  protected static $persistent_attributes = [
    'id' => [T::Integer, false, 'auto_increment'],
    'num_wheels' => [T::Integer],
    'color' => [T::Enumeration, false, 'ColorEnum']
  ];
  protected static $primary_key = ['id'];
}

Model

A model has to extend the PersistenceModel class. A model is the owner of a specific entity. A model can be accessed everywhere with the public static instance() method. This should however be avoided where possible., (*16)

Models should be placed in model/., (*17)

Variables in a model

A model has a few static variables which must be defined., (*18)

ORM

The constant ORM defines which entity this model is the owner of. This is a string or class., (*19)

const ORM = 'Car';
const ORM = Car::class;
$default_order

This is the default value to use for the order when selecting from the database., (*20)

protected static $default_order = 'num_wheels DESC';

Functions in a model

The following functions can be used on a model, (*21)

find($criteria, $criteria_params, ...) : PersistentEntity[]

Find entities in the database filtered on criteria. The syntax for this should be familiar if you ever worked with PDO in PHP. The $criteria is the WHERE clause of the underlying select statement, you can put ?'s here where variables are. The criteria params are where you fill these variables. Criteria params are automatically filtered and safe for user input., (*22)

CarModel::instance()->find('num_wheels = ? AND color = ?', [$normal_car_wheels, $car_color]);

count($criteria, $criteria_params) : int

Count the number of entities which pass the criteria, same as find(..). Creates statements like SELECT COUNT(*) ... which are faster than counting in PHP., (*23)

exists($entity) : boolean

Check whether or not an entity exists in the database., (*24)

create($entity) : string

Save a new entity into the database. Returns the id of the inserted entity., (*25)

update($entity) : int

Store an entity in the database, replacing the entity with the same primary key., (*26)

delete($entity) : int

Delete an entity from the database., (*27)

Example

model/CarModel.php, (*28)

require_once 'model/entity/Car.php';

class CarModel extends PersistenceModel {
  const ORM = 'Car';

  public function findByColor($color) {
    return $this->find('color = ?', [$color]);
  }
}

index.php, (*29)

require_once 'model/CarModel.php';

$model = CarModel::instance();
$cars = $model->find();
$actual_cars = $model->find('num_wheels = 4');
$yellow_cars = $model->findByColor('yellow');

Database update

This orm can check the models for you. To enable this feature you need to define the global constant DB_CHECK as true. After that you can check the DatabaseAdmin for any updated tables. This only checks tables which are in use and must be done after all models are used. It is also possible to enable automatically updating the database by defining the global constant DB_MODIFY as true. This will update tables according to your models. This will not try to migrate data, so be careful. DB_MODIFY will not drop tables. for this you will need to define DB_DROP as true., (*30)

if (DB_CHECK) {
    $queries = DatabaseAdmin::instance()->getQueries();
    if (!empty($queries)) {
        if (DB_MODIFY) {
            header('Content-Type: text/x-sql');
            header('Content-Disposition: attachment;filename=DB_modify_' . time() . '.sql');
            foreach ($queries as $query) {
                echo $query . ";\n";
            }
            exit;
        } else {
            var_dump($queries);
        }
    }
}

JSON fields

By using T::JSON, a database field can be mapped to an array or object. On save, data is serialized to JSON and can later be deserialized. In the example the $reviews property is a JSON field., (*31)

$model = CarModel::instance();
$car = $model->find()[0];

$review = new CarReview();
$review->userId = '1801';
$review->reviewText = 'Very good car!';

$car->reviews = [$review];
$model->update($car);

To prevent remote code execution only allowed classes can be (de)deserialized. In the third element of the attribute defintion the list of allowed classes should be specified. Also null can be passed to allow all classes., (*32)

Database transactions

To wrap multiple database calls in a transaction you can use Database::transaction(Closure). This function wraps another function in a database transaction. Any exception thrown causes the transaction to be rolled back. If the database is in a transaction this function will just call the Closure without trying to create a new transaction., (*33)

$car = new Car();
Database::transaction(function () use ($car) {
    CarModel::instance()->create($car);
    CarWheelModel::instance()->create($car->getWheels());
});

Dependency Injection

You can provide your own ContainerInterface to DependencyManager, this container will be used for everything. You still need to provide the container with instances of Database, DatabaseAdmin and OrmMemcache., (*34)

$container = $kernel->getContainer();

DependencyManager::setContainer($container);

$container->set(OrmMemcache::class, new OrmMemcache($cachePath));
$container->set(Database::class, new Database($pdo));
$container->set(DatabaseAdmin::class, new DatabaseAdmin($pdo));

It is also possible to leverage the dependency injection provided by the orm. The orm does a very simple way of dependency injection. When a instance of a model is created is created it tries to lookup any dependencies which extend DependencyManager if they are found they are wired into the model and available for use. There can only be one version of a model and this is kept track of in DependencyManager., (*35)

Example

class OwnerModel extends PersistenceModel {
  const ORM = 'Owner';

  /** @var CarModel */
  protected $carModel;

  public function __construct(CarModel $carModel) {
    $this->carModel = $carModel;
  }

  public function getCarsForOwner(Owner $owner) {
    return $this->carModel->find('owner = ?', [$owner->id]);
  }
}

class CarModel extends PersistenceModel {
  const ORM = 'Car';

  public function findByColor($color) {
    return $this->find('color = ?', [$color]);
  }
}
$owner = OwnerModel::instance()->find('id = 1');

$cars = OwnerModel::instance()->getCarsForOwner($owner);

The Versions

19/07 2018

dev-allow_json_mapping

dev-allow_json_mapping https://csrdelft.github.io/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

MIT

The Requires

 

The Development Requires

by Gerben Oolbekkink

18/07 2018

dev-master

9999999-dev https://csrdelft.github.io/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

MIT Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

02/04 2018

1.7.4

1.7.4.0 https://csrdelft.github.io/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

MIT

The Requires

  • php >=7.1

 

The Development Requires

by Gerben Oolbekkink

01/04 2018

v1.7.3

1.7.3.0 https://csrdelft.github.io/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

MIT

The Requires

  • php >=7.1

 

The Development Requires

by Gerben Oolbekkink

01/02 2018

dev-query-object

dev-query-object https://csrdelft.github.io/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

MIT

The Requires

 

The Development Requires

by Gerben Oolbekkink

01/02 2018

v1.7.2

1.7.2.0 https://csrdelft.github.io/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

MIT

The Requires

 

The Development Requires

by Gerben Oolbekkink

03/10 2017

v1.7.1

1.7.1.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

20/09 2017

v1.7

1.7.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

21/08 2017

v2.x-dev

2.9999999.9999999.9999999-dev https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

14/05 2017

v1.6

1.6.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

03/04 2017

v1.5

1.5.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

30/03 2017

v1.3

1.3.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

30/03 2017

v1.4

1.4.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

 

The Development Requires

by Gerben Oolbekkink

09/02 2017

v1.2

1.2.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

  • php >=5.3.0

 

The Development Requires

by Gerben Oolbekkink

08/02 2017

v1.1

1.1.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

  • php >=5.3.0

 

The Development Requires

by Gerben Oolbekkink

08/02 2017

v1.0

1.0.0.0 https://github.com/csrdelft/orm

The creatively named object-relational mapping library for csrdelft.nl

  Sources   Download

Unknown

The Requires

  • php >=5.3.0

 

by Gerben Oolbekkink