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

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. doublemcz/dibi-orm

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

doublemcz/dibi-orm
==================

ORM system based on dibi

1.1.1(11y ago)334[2 issues](https://github.com/doublemcz/dibi-orm/issues)BSD-3-ClausePHP

Since Jan 1Pushed 10y ago2 watchersCompare

[ Source](https://github.com/doublemcz/dibi-orm)[ Packagist](https://packagist.org/packages/doublemcz/dibi-orm)[ RSS](/packages/doublemcz-dibi-orm/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)DependenciesVersions (6)Used By (0)

Dibi ORM - EXPERIMENTAL
=======================

[](#dibi-orm---experimental)

Dibi ORM is lightweight ORM solution based on Dibi. ORM logic comes from Doctrine 2 but is very simplified. Focus is also on performance.

### Installation

[](#installation)

I recommend you to install via Composer.

```
composer require doublemcz/dibi-orm

```

If you do not have Composer, download latest version from GitHub and require bootstrap file.

```
require 'src/dibirom.php'
```

### Initialization

[](#initialization)

```
$parameters = array(
	'database' => array(
		'host' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'dibiorm',
		'driver' => 'mysqli',
	),
	'entityNamespace' => 'App\Entities',
	'proxiesPath' => __DIR__ . '/temp',
	'storage' => new Nette\Caching\Storages\FileStorage('temp'),
);

$databaseManager = new \doublemcz\dibiorm\Manager($parameters);
```

##### Usage in Nette

[](#usage-in-nette)

Put this section into services.neon

```
extensions:
	dibi: Dibi\Bridges\Nette\DibiExtension22

services:
	databaseManager: doublemcz\dibiorm\Manager(%databaseManager%)

parameters:
	databaseManager:
		database:
			host: localhost
			username: userName
			password: password
			database: database
		entityNamespace: App\Entities
		proxiesPath: '%tempDir%/proxies'
		storage: @cacheStorage
```

It is also possible to pass DibiConnection to parameter 'database'

```
parameters:
	databaseManager:
		database: @dibiConnection
```

### Data handling

[](#data-handling)

##### Get an Entity by ID

[](#get-an-entity-by-id)

Find a user with ID = 1

```
$databaseManager->find('User', 1);
```

If user has more columns in primary key, you can pass it in order you defined the key at the entity

```
$user = $databaseManager->find('AnEntityName', 'foo', 'bar');
```

##### Find an Entity by propety

[](#find-an-entity-by-propety)

We can find an Entity by property e-mail

```
$user = $databaseManager->findOneBy('User', array('email' => 'email@domain.com'));
```

##### Get entities in table

[](#get-entities-in-table)

Find all users in table 'users'

```
$users = $databaseManager->findBy('User');
```

You can filter and sort by array. We are trying to find Users in role 'admin' ordered by id desc.

```
$users = $databaseManager
	->findBy(
		'User',
		array('role' => 'admin'),
		array('id' => 'DESC')
	);
```

##### Insert entity to database

[](#insert-entity-to-database)

```
$user = new User();
$user->name = 'Martin';
$databaseManager->persist($user);
$databaseManager->flush();
```

##### Update entity

[](#update-entity)

When you load an entity from repository then the entity is automatically managed by Manager. It means that if you make a change and flush changes over Manager a SQL query is automatically executed.

```
$user = $databaseManager->find('User', 1);
$user->note = 'An updated note on user 1';
$databaseManager->flush();
```

##### Delete entity

[](#delete-entity)

```
$user = $databaseManager->find('User', 1);
$database->delete($user);
$databaseManager->flush();
```

##### Database Manager knows what have changed

[](#database-manager-knows-what-have-changed)

You can flush whenever you want. Manager knows what data have changed and does necessary stuff on flush.

```
$user = $databaseManager->find('User', 1);
$user->note = 'An updated note on user 1';

$user2 = $databaseManager->find('User', 2);
$user2->note = 'An updated note on user 2';

$user3 = $databaseManager->find('User', 3);
$database->delete($user3);
// Flush makes automatically two sql updates and one delete
$databaseManager->flush();
```

### Entity Settings

[](#entity-settings)

All settings are defined by PhpDoc. Every entity must have @table tag to specify the source table defined on class PhpDoc. Every class property that has relation to database column must have tag @column.

##### Defining primary column

[](#defining-primary-column)

Every entity must have primary key. The definition is composed by @primaryKey and @column. If you want set id that was generated from database on create sql query then specify @autoIncrement tag.

##### Relations

[](#relations)

Basic relation are defined by @oneToOne and @oneToMany tag. Both need a join specification tag defined as follow: @join(column="id", referenceColumn="userId"). It says that it is joing column User.id to RelatedTable.userId column.

###### Real example:

[](#real-example)

```
/**
 * @table (name="users")
 */
class User {
	/**
	 * @oneToMany(entity="UserLog")
	 * @join(column="id", referenceColumn="userId")
	 * @var User
	 */
	protected $userLog;

	/**
	 * @return UserLog[]
	 */
	public function getUserLog()
	{
		return  $this->userLog;
	}
}
```

###### Static join parameter

[](#static-join-parameter)

It is also possible to specify static join parameter to filter table by column. Here you can see static join that defines user.type = 'error'. Static join is possible only on @oneToOne and @oneToMany relations.

```
/**
 * @table (name="users")
 */
class User {
	/**
	 * @oneToMany(entity="UserLog")
	 * @join(column="id", referenceColumn="userId")
	 * @staticJoin(column="type", value="error")
	 * @var User
	 */
	protected $errorLog;

	/**
	 * @return UserLog[]
	 */
	public function getErrorLog()
	{
		return  $this->errorLog;
	}
}
```

##### Relation @manyToMany

[](#relation-manytomany)

Relation many-to-many is used when your data are connected over relation table.

```
/**
 * @manyToMany(entity="AnEntityName", joiningTable="joining_table")
 * @joinPrimary(column="id", referenceColumn="userId")
 * @joinSecondary(column="userLogId", referenceColumn="id")
 * @var AnEntityName[]
 */
protected $foo;
```

### Events

[](#events)

Manager has event handling based on methods included in the Class. We have Entity events at this moment:

- beforeCreateEvent
- beforeUpdateEvent

#### Examples of event usage.

[](#examples-of-event-usage)

There you can see how we can update an entity **before** create or update sql is executed.

```
/**
 * @param Manager $manager
 */
public function beforeCreateEvent(Manager $manager)
{
	$this->createdAt = new \DateTime();
}

public function beforeUpdateEvent(Manager $manager)
{
	$this->updatedAt = new \DateTime();
}
```

### Example of User entity definition

[](#example-of-user-entity-definition)

```
