Nette Database
Nette Database is a powerful and elegant database layer for PHP with a focus on simplicity and smart features. It offers two complementary ways to work with your data – using the Explorer for rapid development, or the SQL way for full control over queries.
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();