This repository has been archived by the owner on May 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ModelLoader.php
99 lines (80 loc) · 2 KB
/
ModelLoader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
/**
* Copyright (C) 2011 by Igor Hlina ([email protected])
*/
namespace Diggriola;
use Nette\DI\IContainer,
Nette\Diagnostics\Debugger,
PDO,
NotORM,
NotORM_Cache_Session,
NotORM_Structure_Convention;
/**
* Service for Model loading & database connection
*
* @package Diggriola
* @author Igor Hlina <[email protected]>
* @license license.txt MIT
* @version 1.0
* @link https://github.com/srigi/Diggriola
* @link http://wiki.nette.org/cs/cookbook/jednoduchy-model-s-notorm
*
*/
class ModelLoader extends \Nette\Object
{
/**
* @var NotORM
*/
private $connection;
/**
* @var array Models pool
*/
private $models = array();
/**
* Connection factory. Connects to DB.
*
* @param Nette\DI\IContainer $container
* @return NotORM
*/
public static function dbConnect(IContainer $container)
{
$db = $container->params['database'];
$dsn = (isset($db['port']))
? "$db[driver]:host=$db[host];dbname=$db[database];port=$db[port]"
: "$db[driver]:host=$db[host];dbname=$db[database]";
$pdo = new PDO($dsn, $db['username'], $db['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query('SET NAMES utf8');
$conn = new NotORM($pdo, new NotORM_Structure_Convention('id', '%s_id', '%ss'), new NotORM_Cache_Session);
if (isset($db['profiler']) && $db['profiler']) {
$panel = Panel::getInstance();
$panel->setPlatform($db['driver']);
Debugger::addPanel($panel);
$conn->debug = function($query, $parameters) {
Panel::getInstance()->logQuery($query, $parameters);
};
}
return $conn;
}
/**
* @param NotORM $connection
*/
public function __construct($connection)
{
$this->connection = $connection;
}
/**
* Return required Model. Instantiate if not in pool.
*
* @param string $model
* @return mixed
*/
public function getModel($model)
{
if (!isset($this->models[$model])) {
$class = 'Model\\' . ucfirst($model);
$this->models[$model] = new $class($this->connection);
}
return $this->models[$model];
}
}