Nette Database

Nette Database is a powerful and elegant database layer for PHP, known for its simplicity and smart features. It requires no complex configuration or entity generation, allowing you to start working with it immediately.

Installation:

composer require nette/database

Connection and Configuration

To connect to the database, simply create an instance of the Nette\Database\Connection class:

$database = new Nette\Database\Connection($dsn, $user, $password);

The $dsn (data source name) parameter is the same as used by PDO, eg host=127.0.0.1;dbname=test. In the case of failure it throws Nette\Database\ConnectionException.

However, a more sophisticated way offers application configuration. We will add a database section and it creates the required objects and a database panel in the Tracy bar.

database:
	dsn: 'mysql:host=127.0.0.1;dbname=test'
	user: root
	password: password

The connection object we receive as a service from a DI container, for example:

class Model
{
	private $database;

	// pass Nette\Database\Context to work with the Database Explorer layer
	public function __construct(Nette\Database\Connection $database)
	{
		$this->database = $database;
	}
}

For more information, see database configuration.

Transactions

There are three methods for dealing with transactions:

$database->beginTransaction();

$database->commit();

$database->rollback();
version: 4.0 3.x 2.x