PHPackages                             mariano/li3\_doctrine2 - 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. mariano/li3\_doctrine2

ActiveLithium-library[Database &amp; ORM](/categories/database)

mariano/li3\_doctrine2
======================

li3\_doctrine2 offers Doctrine2 as an ORM for the Lithium framework

241.4k6[2 issues](https://github.com/mariano/li3_doctrine2/issues)PHPCI failing

Since Jul 10Pushed 10y ago4 watchersCompare

[ Source](https://github.com/mariano/li3_doctrine2)[ Packagist](https://packagist.org/packages/mariano/li3_doctrine2)[ RSS](/packages/mariano-li3-doctrine2/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

li3\_doctrine2 offers integration between \[the most RAD PHP framework\] [lithium](http://lithify.me)and possibly the best PHP 5.3 ORM out there: [Doctrine2](http://www.doctrine-project.org) [doctrine2](http://www.doctrine-project.org)

License
=======

[](#license)

li3\_doctrine2 is released under the \[MIT License\] [license](http://www.opensource.org/licenses/mit-license.php).

Installation
============

[](#installation)

Install [Composer](http://getcomposer.org) [composer](http://getcomposer.org) if you didn't already. Then add li3\_doctrine2 as a required package (together with Doctrine and migrations):

```
{
	"config": {
		"vendor-dir": "libraries"
	},
	"require": {
		"doctrine/orm": ">=2.1",
		"doctrine/migrations": "dev-master",
		"mariano/li3_doctrine2": "dev-master"
	}
}
```

Finally, tell composer to install these packages:

```
$ composer install
```

You will now need to ensure that Composer's autoload file is loaded so all vendor classes (such as Doctrine) can be loaded, and then load the li3\_doctrine2 library. Place the following at the end of your `app/config/bootstrap/libraries.php` file:

```
require_once(LITHIUM_LIBRARY_PATH . '/autoload.php');

Libraries::add('li3_doctrine2', [
	'path' => LITHIUM_LIBRARY_PATH . '/mariano/li3_doctrine2'
]);
```

Usage
=====

[](#usage)

Defining a connection
---------------------

[](#defining-a-connection)

Setting up a connection with li3\_doctrine2 is easy. All you need to do is add the following to your `app/config/bootstrap/connections.php` file (make sure to edit the settings to match your host, without altering the `type`setting):

```
Connections::add('default', [
	'type' => 'Doctrine',
	'driver' => 'pdo_mysql',
	'host' => 'localhost',
	'user' => 'root',
	'password' => 'password',
	'dbname' => 'my_db'
]);
```

### Working with master-slave connections

[](#working-with-master-slave-connections)

Thanks to Doctrine, master/slave connection queries can be done quite easy. All you have to do is slightly change your connection definition so you can use the `MasterSlaveConnection` wrapper class, and instead of simply specifying a single server, you give the details for the master server, and each of the slave servers. Example:

```
Connections::add('default', [
	'type' => 'Doctrine',
	'driver' => 'pdo_mysql',
	'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
    'master' => [
		'host' => 'master.example.com',
		'user' => 'root',
		'password' => 'password',
		'dbname' => 'my_db'
	],
    'slaves' => [
		[
			'host' => 'slave1.example.com',
			'user' => 'root',
			'password' => 'password',
			'dbname' => 'my_db'
		],
		[
			'host' => 'slave2.example.com',
			'user' => 'root',
			'password' => 'password',
			'dbname' => 'my_db'
		]
    ]
]);
```

Working with models
-------------------

[](#working-with-models)

### Creating models

[](#creating-models)

When looking to create your doctrine models, you have two choices: you can have them follow your custom class hierarchy (or none at all), or you could have them extend from the `BaseEntity` class provided by this library. The advantage of choosing the later is that your models will have lithium's validation support, and can be better integrated with the custom adapters provided by this library (such as for session management or for authorization.)

> If you still want validation support but do not wish to extend `BaseEntity`your models should implement the `li3_doctrine2\models\IModel` interface.

Let us create a `User` model. Following doctrine's \[basic mapping guide\] [doctrine-mapping-guide](http://www.doctrine-project.org/docs/orm/2.1/en/reference/basic-mapping.html) we'll use annotations to define the properties, and we will also include lithium validation rules (that's why we are choosing to extend this model from `BaseEntity`):

```

```

You should note that if you make your model properties private, each property **must have** a getter and a setter method, otherwise validation and other features provided by `BaseEntity` won't work.

### Using the Doctrine shell to generate the schema

[](#using-the-doctrine-shell-to-generate-the-schema)

Once you have your model(s) created, you can use doctrine's shell to generate the schema. li3\_doctrine2 offers a wrapper for doctrine's shell that reutilizes lithium's connection details. To run the access the core directory of your application and do:

```
$ libraries/li3_doctrine2/bin/doctrine
```

That will give you all the available commands. For example, to get the SQL you should run to create the schema for your models, do:

```
$ libraries/li3_doctrine2/bin/doctrine orm:schema-tool:create --dump-sql
```

which will give an output similar to the following:

```
CREATE TABLE users (
	id INT AUTO_INCREMENT NOT NULL,
	email VARCHAR(255) NOT NULL,
	password LONGTEXT NOT NULL,
	name VARCHAR(255) NOT NULL,
	UNIQUE INDEX UNIQ_1483A5E9E7927C74 (email),
	PRIMARY KEY(id)
) ENGINE = InnoDB
```

### Getting the entity manager

[](#getting-the-entity-manager)

Doctrine's `EntityManager` is the way we have to interact with the underlying database, which means we'll always need to obtain it. You can do so by running the following code (change `default` to the name of your connection as defined in `app/config/connections.php`):

```
$em = \lithium\data\Connections::get('default')->getEntityManager();
```

If your models extend from `BaseEntity`, then all of them have a static method named `getEntityManager()` (which uses a static property inherited from `BaseEntity` named `$connectionName` to figure out what connection to use):

```
$em = User::getEntityManager();
```

`BaseEntity` also offers a `getRepository()` method which will return the repository for the model (see the section *Fetching record* below.)

### Fetching records

[](#fetching-records)

Once you have the entity manager, you can fetch a user with ID 1 (notice how we use the fully qualified class name for the model) using the entity manager:

```
$user = $em->find('app\models\User', 1);
```

or using model repositories:

```
$user = $em->getRepository('app\models\User')->findOneById(1);
```

If your model extends from `BaseEntity`, then the above could be retwritten as:

```
$user = User::getRepository()->findOneById(1);
```

If you want to find out more about querying models with Doctrine, go through its \[Querying guide\] [doctrine-querying-guide](http://www.doctrine-project.org/docs/orm/2.1/en/reference/working-with-objects.html#querying).

### Creating/Updating/Deleting records

[](#creatingupdatingdeleting-records)

Records are persisted (or removed) though the entity manager, as shown in Doctrine's \[Persisting guide\] [doctrine-persisting-guide](http://www.doctrine-project.org/docs/orm/2.1/en/reference/working-with-objects.html#persisting-entities).

One thing to note is that if your models extend from `BaseEntity`, you have validation rules defined for them, and the data you provide does not validate, persisting it will throw a `ValidateException` (the following example uses the `User` model we defined earlier):

```
$user = new User();
$user->setName('John Doe');
$user->setEmail('bademail@');

try {
	$em->persist($user);
	$em->flush();
} catch(\li3_doctrine2\models\ValidateException $e) {
	echo $e->getMessage();
}
```

You should also note that `BaseEntity` provides a method named `set()` which comes very handy if the user data is to be populated from a form submission. If so, the above code could be rewritten as:

> You may notice that we send a list of field names as the second argument to the `set()` method. More about this in the section *Field whitelist in BaseEntity::set()*

```
$user = new User();
$user->set($this->request->data, ['name', 'email']);

try {
	$em->persist($user);
	$em->flush();
} catch(\li3_doctrine2\models\ValidateException $e) {
	echo $e->getMessage();
}
```

In this last example, if lithium's Form helper is bound to the record instance, it will properly show validation errors. The following view code uses the `$user` variable from the example above to bind the form to its validation errors:

```
