library database
Database layer for Nette Framework.
fabik/database
Database layer for Nette Framework.
- Wednesday, August 7, 2013
- by fabik
- Repository
- 4 Watchers
- 19 Stars
- 681 Installations
- PHP
- 0 Dependents
- 0 Suggesters
- 2 Forks
- 1 Open issues
- 4 Versions
- 1 % Grown
fabik/database
This is a database layer for Nette Framework based on Nette\Database., (*1)
Installation
Get the source code using Composer (add "fabik/database": "1.1.*" to your composer.json) or directly download Database to your libs directory., (*2)
Example of use
-
Create the database:, (*3)
CREATE TABLE `users` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` char(40) NOT NULL,
`email` varchar(255) NOT NULL,
`firstname` varchar(255) NOT NULL,
`surname` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`username`)
) ENGINE=InnoDB;
CREATE TABLE `articles` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` longtext NOT NULL,
`author_id` int unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY (`author_id`),
FOREIGN KEY (`author_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB;
-
Register the compiler extension in the bootstrapper., (*4)
use Fabik\Database\DatabaseExtension;
$configurator->onCompile[] = function($configurator, $compiler) {
$compiler->addExtension('database', new DatabaseExtension);
};
-
Add the following sections to your config.neon file:, (*5)
nette:
database:
default:
dsn: '%database.driver%:host=%database.host%;dbname=%database.dbname%'
user: %database.user%
password: %database.password%
database:
rowFactory:
classes:
articles: Blog\Article
users: Blog\User
services:
articles: Blog\Articles
users: Blog\Users
-
Create classes for rows (e.g. Article, User) and tables (e.g. Articles, Users):, (*6)
<?php
namespace Blog;
use Fabik\Database\ActiveRow,
Fabik\Database\Table;
class Article extends ActiveRow
{
}
class User extends ActiveRow
{
/** @return string */
public function getRealname()
{
return "$this->firstname $this->surname";
}
/** @param string */
public function setRealname($realname)
{
list($this->firstname, $this->surname) = explode(' ', $realname);
}
}
class Articles extends Table
{
protected $name = 'articles';
}
class Users extends Table
{
protected $name = 'users';
}
-
Now you can use it as follows:, (*7)
$articles = $container->articles;
foreach ($articles->findAll() as $article) {
echo "$article->title was written by $article->author->realname\n";
}