Skip to content
This repository was archived by the owner on Mar 25, 2025. It is now read-only.

Commit 70f9409

Browse files
committedMar 31, 2018
example configurations was added
1 parent 54e54ab commit 70f9409

20 files changed

+378
-100
lines changed
 

‎extra/configs/mysql.php

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
/**
3+
* More details about PDO-MySQL driver:
4+
* @link http://php.net/manual/en/ref.pdo-mysql.connection.php
5+
*/
6+
7+
return [
8+
'mysql' => [
9+
'driver' => 'mysql',
10+
'host' => '127.0.0.1', // optional, default: 127.0.0.1
11+
'port' => '3306', // optional, default: 3306
12+
'username' => 'admin',
13+
'password' => 'admin_pass',
14+
'dbname' => 'database',
15+
'prefix' => 'prefix_',
16+
'collation' => 'utf8_unicode_ci', // optional, default: utf8_unicode_ci
17+
'charset' => 'utf8', // optional, default: utf8
18+
],
19+
];

‎extra/configs/mysql_socket.php

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
return [
4+
'mysql_socket' => [
5+
'driver' => 'mysql',
6+
'unix_socket' => '/var/run/mysqld/mysqld.sock',
7+
'username' => 'admin',
8+
'password' => 'admin_pass',
9+
'dbname' => 'database',
10+
],
11+
];

‎extra/configs/pgsql.php

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
/**
3+
* More details about PDO-PostgreSQL driver:
4+
* @link http://php.net/manual/en/ref.pdo-pgsql.connection.php
5+
*
6+
* List of all available options of postgresql 10 driver:
7+
* @link https://www.postgresql.org/docs/10/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS
8+
*
9+
* List of all available charsets:
10+
* @link https://www.postgresql.org/docs/current/static/multibyte.html
11+
*/
12+
13+
return [
14+
'pgsql' => [
15+
'driver' => 'pgsql',
16+
'host' => '127.0.0.1', // optional, default: 127.0.0.1
17+
'port' => '5432', // optional, default: 5432
18+
'username' => 'admin',
19+
'password' => 'admin_pass',
20+
'dbname' => 'database',
21+
'prefix' => 'prefix_',
22+
'client_encoding' => 'UTF8' // optional, default: your local configuration
23+
],
24+
];

‎extra/configs/pgsql_socket.php

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
/**
3+
* More details about PDO-PostgreSQL driver:
4+
* @link http://php.net/manual/en/ref.pdo-pgsql.connection.php
5+
*
6+
* List of all available options of postgresql 10 driver:
7+
* @link https://www.postgresql.org/docs/10/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS
8+
*
9+
* List of all available charsets:
10+
* @link https://www.postgresql.org/docs/current/static/multibyte.html
11+
*/
12+
13+
/**
14+
* For socket connection you need to remove 'host' and 'port'
15+
* items from array.
16+
*/
17+
18+
return [
19+
'pgsql_socket' => [
20+
'driver' => 'pgsql',
21+
'username' => 'admin',
22+
'password' => 'admin_pass',
23+
'dbname' => 'database',
24+
],
25+
];

‎extra/database.php

+7-10
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,12 @@
22

33
return [
44
'default' => [
5-
'driver' => 'mysql',
6-
'host' => 'localhost',
7-
'port' => 3306,
8-
'prefix' => 'prefix_',
9-
'collation' => 'utf8_unicode_ci',
10-
'charset' => 'utf8',
11-
'database' => 'dummy',
12-
'username' => 'user',
13-
'password' => 'user_pass'
5+
'driver' => 'pgsql',
6+
'host' => '127.0.0.1', // optional, default: 127.0.0.1
7+
'port' => '5432', // optional, default: 5432
8+
'username' => 'admin',
9+
'password' => 'admin_pass',
10+
'dbname' => 'database',
11+
'prefix' => 'prefix_'
1412
],
15-
'mongo' => []
1613
];

‎extra/test.php

+13-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,19 @@
33

44
$config = new \DrMVC\Config();
55
$config->load(__DIR__ . '/database.php', 'database');
6-
//print_r($config);
6+
print_r($config);
77

88
$model = new \DrMVC\Models\Test($config->get('database'));
99
print_r($model);
10+
11+
// Direct call from model
12+
$test = $model->select('select * from prefix_test;');
13+
print_r($test);
14+
15+
// Call model's method of select
16+
$test = $model->test_select();
17+
print_r($test);
18+
19+
// Call model's method of insert
20+
$test = $model->test_insert();
21+
print_r($test);

‎src/Database/Database.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ public function __construct(ConfigInterface $config)
3434
public function getInstance(string $collection): QueryInterface
3535
{
3636
$class = $this->getDriver();
37-
return new $class($this->getConfig(), $collection);
37+
$instance = new $class($this->getConfig(), $collection);
38+
return $instance->connect();
3839
}
3940

4041
/**

‎src/Database/Drivers/Driver.php

+43-19
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,6 @@ abstract class Driver implements DriverInterface, QueryInterface
1111
*/
1212
protected $_connection;
1313

14-
/**
15-
* @var string
16-
*/
17-
private $_dsn;
18-
1914
/**
2015
* @var ConfigInterface
2116
*/
@@ -36,7 +31,7 @@ abstract class Driver implements DriverInterface, QueryInterface
3631
public function __construct(ConfigInterface $config, string $collection)
3732
{
3833
$this->setConfig($config);
39-
$this->setCollection($this->getConfig()->get('prefix') . $collection);
34+
$this->setCollection($this->getParam('prefix') . $collection);
4035
}
4136

4237
/**
@@ -53,6 +48,33 @@ abstract public function connect(): DriverInterface;
5348
*/
5449
abstract public function disconnect(): DriverInterface;
5550

51+
/**
52+
* Generate DSN by parameters in config
53+
*
54+
* @param $config
55+
* @return string
56+
*/
57+
abstract protected function genDsn($config): string;
58+
59+
/**
60+
* Generate DSN by data in config
61+
*
62+
* @return string
63+
*/
64+
public function getDsn(): string
65+
{
66+
// Get all parameters
67+
$config = $this->getConfig()->get();
68+
69+
// Get driver of connection
70+
$driver = strtolower($config['driver']);
71+
72+
// Generate DSN by parameters in config
73+
$dsn = $this->genDsn($config);
74+
75+
return "$driver:$dsn";
76+
}
77+
5678
/**
5779
* @param string $collection
5880
* @return DriverInterface
@@ -72,6 +94,8 @@ public function getCollection(): string
7294
}
7395

7496
/**
97+
* Save current config
98+
*
7599
* @param ConfigInterface $config
76100
* @return DriverInterface
77101
*/
@@ -82,6 +106,8 @@ public function setConfig(ConfigInterface $config): DriverInterface
82106
}
83107

84108
/**
109+
* Return config object
110+
*
85111
* @return ConfigInterface
86112
*/
87113
public function getConfig(): ConfigInterface
@@ -90,24 +116,20 @@ public function getConfig(): ConfigInterface
90116
}
91117

92118
/**
93-
* @param string $dsn
94-
* @return DriverInterface
95-
*/
96-
public function setDsn(string $dsn): DriverInterface
97-
{
98-
$this->_dsn = $dsn;
99-
return $this;
100-
}
101-
102-
/**
103-
* @return string
119+
* Get some parameter from config by keyname
120+
*
121+
* @param string $param
122+
* @return mixed
104123
*/
105-
public function getDsn(): string
124+
public function getParam(string $param)
106125
{
107-
return $this->_dsn;
126+
$result = $this->getConfig()->get($param);
127+
return $result ?? null;
108128
}
109129

110130
/**
131+
* Save connection with database via PDO drive
132+
*
111133
* @param \PDO $connection
112134
* @return DriverInterface
113135
*/
@@ -118,6 +140,8 @@ public function setConnection(\PDO $connection): DriverInterface
118140
}
119141

120142
/**
143+
* Get current PDO connection
144+
*
121145
* @return \PDO
122146
*/
123147
public function getConnection(): \PDO

‎src/Database/Drivers/DriverInterface.php

+17-5
Original file line numberDiff line numberDiff line change
@@ -18,35 +18,47 @@ public function setCollection(string $collection): DriverInterface;
1818
public function getCollection(): string;
1919

2020
/**
21+
* Save current config
22+
*
2123
* @param ConfigInterface $config
2224
* @return DriverInterface
2325
*/
2426
public function setConfig(ConfigInterface $config): DriverInterface;
2527

2628
/**
29+
* Return config object
30+
*
2731
* @return ConfigInterface
2832
*/
2933
public function getConfig(): ConfigInterface;
3034

3135
/**
36+
* Save connection with database via PDO drive
37+
*
3238
* @param $connection
3339
* @return DriverInterface
3440
*/
3541
public function setConnection(\PDO $connection): DriverInterface;
3642

3743
/**
44+
* Get current PDO connection
45+
*
3846
* @return \PDO
3947
*/
4048
public function getConnection(): \PDO;
4149

4250
/**
43-
* @param string $dsn
44-
* @return DriverInterface
51+
* Generate DSN by data in config
52+
*
53+
* @return string
4554
*/
46-
public function setDsn(string $dsn): DriverInterface;
55+
public function getDsn(): string;
4756

4857
/**
49-
* @return string
58+
* Get some parameter from config by keyname
59+
*
60+
* @param string $param
61+
* @return mixed
5062
*/
51-
public function getDsn(): string;
63+
public function getParam(string $param);
5264
}

‎src/Database/Drivers/Mongo.php

+3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
*/
1212
class Mongo extends NoSQL
1313
{
14+
const DEFAULT_HOST = 'localhost';
15+
const DEFAULT_PORT = '27017';
16+
1417
// /**
1518
// * DMongoDB constructor
1619
// *

‎src/Database/Drivers/Mysql.php

+59-26
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,78 @@
22

33
namespace DrMVC\Database\Drivers;
44

5-
use DrMVC\Config\ConfigInterface;
5+
use DrMVC\Database\SQLException;
66

77
class Mysql extends SQL
88
{
9-
const DEFAULT_HOST = 'localhost';
10-
const DEFAULT_PORT = 3306;
9+
const DEFAULT_HOST = '127.0.0.1';
10+
const DEFAULT_PORT = '3306';
11+
const DEFAULT_CHARSET = 'utf8';
12+
const DEFAULT_COLLATION = 'utf8_unicode_ci';
1113

12-
public function __construct(ConfigInterface $config, string $collection)
13-
{
14-
parent::__construct($config, $collection);
15-
$db_host = $this->getHost();
16-
$db_port = $this->getPort();
17-
$db_auth = $this->getAuth();
18-
$db_driv = $this->getConfig()->get('driver');
19-
$db_name = $this->getConfig()->get('database');
20-
21-
$dsn = "$db_driv://$db_auth$db_host:$db_port/$db_name";
22-
23-
$this->setDsn($dsn);
24-
}
14+
/**
15+
* @link https://secure.php.net/manual/en/ref.pdo-mysql.connection.php
16+
*
17+
* The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:
18+
*/
19+
const AVAILABLE_ELEMENTS = [
20+
'host',
21+
'port',
22+
'dbname',
23+
'unix_socket'
24+
];
2525

26-
private function getHost(): string
26+
/**
27+
* Generate DSN by parameters in config
28+
*
29+
* @param array $config
30+
* @return string
31+
*/
32+
public function genDsn($config): string
2733
{
28-
$host = $this->getConfig()->get('host');
29-
return $host ?? self::DEFAULT_HOST;
34+
// Parse config
35+
$dsn = '';
36+
foreach ($config as $key => $value) {
37+
if (\in_array($key, self::AVAILABLE_ELEMENTS, false)) {
38+
$dsn .= "$key=$value;";
39+
}
40+
}
41+
return $dsn;
3042
}
3143

32-
private function getPort(): int
44+
/**
45+
* Initiate connection to database
46+
*
47+
* @return DriverInterface
48+
*/
49+
public function connect(): DriverInterface
3350
{
34-
$port = $this->getConfig()->get('port');
35-
return $port ?? self::DEFAULT_PORT;
51+
$connection = null;
52+
try {
53+
$connection = new \PDO(
54+
$this->getDsn(),
55+
$this->getParam('username'),
56+
$this->getParam('password'),
57+
$this->getOptions()
58+
);
59+
} catch (SQLException $e) {
60+
// __construct
61+
}
62+
63+
$this->setConnection($connection);
64+
return $this;
3665
}
3766

38-
private function getAuth(): string
67+
private function getOptions(): array
3968
{
40-
$user = $this->getConfig()->get('username');
41-
$pass = $this->getConfig()->get('password');
69+
// Current charset
70+
$charset = $this->getParam('charset') ?? self::DEFAULT_CHARSET;
71+
72+
// Current collation
73+
$collation = $this->getParam('collation') ?? self::DEFAULT_COLLATION;
4274

43-
return ($user && $pass) ? $user . ':' . $pass . '@' : '';
75+
// Return array of options
76+
return [\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '$charset' COLLATE '$collation'"];
4477
}
4578

4679
}

‎src/Database/Drivers/Pgsql.php

+63-5
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,71 @@
22

33
namespace DrMVC\Database\Drivers;
44

5-
use DrMVC\Config\ConfigInterface;
6-
75
class Pgsql extends SQL
86
{
9-
public function __construct(ConfigInterface $config)
7+
const DEFAULT_HOST = '127.0.0.1';
8+
const DEFAULT_PORT = '5432';
9+
10+
/**
11+
* @link https://secure.php.net/manual/en/ref.pdo-pgsql.connection.php
12+
* @link https://www.postgresql.org/docs/8.3/static/libpq-connect.html
13+
*
14+
* The PDO_PGSQL Data Source Name (DSN) is composed of the following elements:
15+
*/
16+
const AVAILABLE_ELEMENTS = [
17+
'host',
18+
'hostaddr',
19+
'port',
20+
'dbname',
21+
22+
/**
23+
* These two parameters below is not needed, because we can put user/pass
24+
* as parameters of PDO class, you can read more by link
25+
* @link https://secure.php.net/manual/en/pdo.construct.php
26+
*/
27+
//'user',
28+
//'password',
29+
30+
'passfile',
31+
'connect_timeout',
32+
'client_encoding',
33+
'options',
34+
'application_name',
35+
'fallback_application_name',
36+
'keepalives',
37+
'keepalives_idle',
38+
'keepalives_interval',
39+
'keepalives_count',
40+
'tty',
41+
'sslmode',
42+
'requiressl',
43+
'sslcompression',
44+
'sslcert',
45+
'sslkey',
46+
'sslrootcert',
47+
'sslcrl',
48+
'requirepeer',
49+
'krbsrvname',
50+
'gsslib',
51+
'service',
52+
'target_session_attrs'
53+
];
54+
55+
/**
56+
* Generate DSN by parameters in config
57+
*
58+
* @param array $config
59+
* @return string
60+
*/
61+
public function genDsn($config): string
1062
{
11-
parent::__construct($config);
12-
$this->setDsn('pgsql:' . $this->getConfig()->get('path'));
63+
// Parse config
64+
$dsn = '';
65+
foreach ($config as $key => $value) {
66+
if (\in_array($key, self::AVAILABLE_ELEMENTS, false)) {
67+
$dsn .= "$key=$value;";
68+
}
69+
}
70+
return $dsn;
1371
}
1472
}

‎src/Database/Drivers/QueryInterface.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ interface QueryInterface
1414
public function select(string $query, array $data);
1515

1616
/**
17-
* Exec query without return, create table for example
17+
* Execute some query in silence mode, create table for example
1818
*
1919
* @param string $query
2020
* @return mixed

‎src/Database/Drivers/SQL.php

+25-12
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace DrMVC\Database\Drivers;
44

5+
use DrMVC\Database\SQLException;
6+
57
abstract class SQL extends Driver
68
{
79
/**
@@ -11,8 +13,18 @@ abstract class SQL extends Driver
1113
*/
1214
public function connect(): DriverInterface
1315
{
14-
$connection = new \PDO($this->getDsn());
16+
$connection = null;
17+
try {
18+
$connection = new \PDO(
19+
$this->getDsn(),
20+
$this->getParam('username'),
21+
$this->getParam('password')
22+
);
23+
} catch (SQLException $e) {
24+
// __construct
25+
}
1526
$this->setConnection($connection);
27+
1628
return $this;
1729
}
1830

@@ -67,35 +79,36 @@ public function exec(string $query)
6779
* Insert in database and return of inserted element
6880
*
6981
* @param array $data array of columns and values
82+
* @param string $id field name of ID which must be returned
7083
* @return mixed
7184
*/
72-
public function insert(array $data)
85+
public function insert(array $data, string $id = null)
7386
{
7487
// Current table
75-
$table = $this->getConnection();
88+
$table = $this->getCollection();
7689

7790
// Generate array of fields for insert
7891
$fieldNames = implode(',', array_keys($data));
7992

8093
// Generate line with data for update
81-
$fieldDetails = !empty($data)
82-
? $this->genFields($data)
83-
: '';
94+
$fieldDetails = ':' . implode(', :', array_keys($data));
8495

8596
// Prepare query
86-
$statement = $this->getConnection()->prepare("INSERT INTO $table ($fieldNames) VALUES ($fieldDetails)");
97+
$statement = $this->_connection->prepare("INSERT INTO $table ($fieldNames) VALUES ($fieldDetails)");
8798

88-
// Bind field values
99+
// Bind values
89100
foreach ($data as $key => $value) {
90-
$statement->bindValue(":field_$key", $value);
101+
$statement->bindValue(":$key", $value);
91102
}
92103

93104
// Execute operation
94105
$statement->execute();
95106

96-
// Return ID of inserted element
97-
return $this->getConnection()->lastInsertId();
98-
// TODO: Need to add ability to set the name of ID field (not only "id")
107+
return (null !== $id)
108+
// Return ID of inserted element
109+
? $this->getConnection()->lastInsertId($id)
110+
// Return count of affected rows
111+
: $statement->rowCount();
99112
}
100113

101114
/**

‎src/Database/Exception.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*/
99
class Exception extends \Exception
1010
{
11-
public function __construct(string $message = "", int $code = 0, \Throwable $previous = null)
11+
public function __construct(string $message = '', int $code = 0, \Throwable $previous = null)
1212
{
1313
parent::__construct($message, $code, $previous);
1414

‎src/Database/Model.php

+30-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ public function getCollection()
8787
*
8888
* @param QueryInterface $instance
8989
*/
90-
public function setInstance(QueryInterface $instance)
90+
private function setInstance(QueryInterface $instance)
9191
{
9292
$this->_instance = $instance;
9393
}
@@ -102,4 +102,33 @@ public function getInstance(): QueryInterface
102102
return $this->_instance;
103103
}
104104

105+
public function update(array $data, array $where = [])
106+
{
107+
return $this->getInstance()->update($data, $where);
108+
}
109+
110+
public function delete(array $where)
111+
{
112+
return $this->getInstance()->delete($where);
113+
}
114+
115+
public function exec(string $query)
116+
{
117+
return $this->getInstance()->exec($query);
118+
}
119+
120+
public function insert(array $data)
121+
{
122+
return $this->getInstance()->insert($data);
123+
}
124+
125+
public function select(string $query, array $data = [])
126+
{
127+
return $this->getInstance()->select($query, $data);
128+
}
129+
130+
public function truncate()
131+
{
132+
return $this->getInstance()->truncate();
133+
}
105134
}

‎src/Database/ModelInterface.php

+2-9
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44

55
use DrMVC\Database\Drivers\QueryInterface;
66

7-
interface ModelInterface
7+
interface ModelInterface extends QueryInterface
88
{
99
/**
10-
* Get current connection name
10+
* Get current database name
1111
*
1212
* @return string
1313
*/
@@ -20,13 +20,6 @@ public function getConnection(): string;
2020
*/
2121
public function getCollection();
2222

23-
/**
24-
* Set database instance
25-
*
26-
* @param QueryInterface $instance
27-
*/
28-
public function setInstance(QueryInterface $instance);
29-
3023
/**
3124
* Get database instance
3225
*

‎src/Database/SQLException.php

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace DrMVC\Database;
4+
5+
/**
6+
* Class SQLException
7+
* @package DrMVC\Database
8+
*/
9+
class SQLException extends \PDOException
10+
{
11+
public function __construct(string $message = '', int $code = 0, \Throwable $previous = null)
12+
{
13+
parent::__construct($message, $code, $previous);
14+
15+
error_log(
16+
'Uncaught Error: ' . $this->getMessage() . ' in ' . $this->getFile() . ':' . $this->getLine() . "\n"
17+
. "Stack trace:\n" . $this->getTraceAsString() . "\n"
18+
. ' thrown in ' . $this->getFile() . ' on line ' . $this->getLine()
19+
);
20+
}
21+
}

‎src/Model.php

-8
This file was deleted.

‎src/Models/Test.php

+12-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,20 @@
22

33
namespace DrMVC\Models;
44

5-
use DrMVC\Model;
5+
use DrMVC\Database\Model;
66

77
class Test extends Model
88
{
99
protected $collection = 'test';
10+
11+
public function test_select()
12+
{
13+
return $this->select('select * from prefix_test');
14+
}
15+
16+
public function test_insert()
17+
{
18+
$data = ['test' => 'zzz'];
19+
return $this->insert($data);
20+
}
1021
}

0 commit comments

Comments
 (0)
This repository has been archived.