2018-01-10 10:47:03 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Console\Services;
|
|
|
|
|
2018-02-21 12:33:09 +08:00
|
|
|
use PDO;
|
2018-01-10 10:47:03 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Class Database
|
|
|
|
*/
|
|
|
|
class Database
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Create the base connection DSN, optionally include the DB name
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-03-20 09:50:40 +08:00
|
|
|
* @param $host
|
|
|
|
* @param $port
|
2018-01-10 10:47:03 +08:00
|
|
|
* @param null $name
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-01-10 10:47:03 +08:00
|
|
|
* @return string
|
|
|
|
*/
|
2018-03-20 09:50:40 +08:00
|
|
|
public function createDsn($host, $port, $name = null)
|
2018-01-10 10:47:03 +08:00
|
|
|
{
|
|
|
|
$conn = config('database.default');
|
|
|
|
$dsn = "$conn:host=$host;port=$port";
|
2018-03-20 09:50:40 +08:00
|
|
|
if (filled($name)) {
|
2018-01-10 10:47:03 +08:00
|
|
|
$dsn .= ';dbname='.$name;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $dsn;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param $dsn
|
|
|
|
* @param $user
|
|
|
|
* @param $pass
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-01-10 10:47:03 +08:00
|
|
|
* @throws \PDOException
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
|
|
|
* @return PDO
|
2018-01-10 10:47:03 +08:00
|
|
|
*/
|
|
|
|
public function createPDO($dsn, $user, $pass)
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$conn = new PDO($dsn, $user, $pass);
|
|
|
|
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
|
|
|
|
} catch (\PDOException $e) {
|
|
|
|
throw $e;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $conn;
|
|
|
|
}
|
|
|
|
}
|