Create database connection using configuration then do a test
This commit is contained in:
parent
f56503a4d4
commit
1235bd4148
11
App/Config.php
Normal file
11
App/Config.php
Normal file
@ -0,0 +1,11 @@
|
||||
<?php
|
||||
namespace App;
|
||||
|
||||
class Config
|
||||
{
|
||||
const
|
||||
DB_HOST = '127.0.0.1',
|
||||
DB_DB = 'cfp_test',
|
||||
DB_UNAME = 'root',
|
||||
DB_PWD = 'root';
|
||||
}
|
64
Core/Model.php
Normal file
64
Core/Model.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
namespace Core;
|
||||
|
||||
use App\Config;
|
||||
|
||||
class Model
|
||||
{
|
||||
protected static $dsn;
|
||||
|
||||
protected static function connectDB()
|
||||
{
|
||||
static $conn = null;
|
||||
|
||||
if (!$conn) {
|
||||
try {
|
||||
$dsn = 'mysql:host='.Config::DB_HOST.';dbname='.Config::DB_DB;
|
||||
$conn = new \PDO($dsn, Config::DB_UNAME, Config::DB_PWD);
|
||||
|
||||
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
} catch (PDOException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
return $conn;
|
||||
}
|
||||
|
||||
public function createTable()
|
||||
{
|
||||
$sql = "CREATE TABLE IF NOT EXISTS pengumuman (
|
||||
id int(3) NOT NULL AUTO_INCREMENT,
|
||||
category int(3) NOT NULL,
|
||||
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expire_at timestamp NOT NULL,
|
||||
creator int(3) NOT NULL,
|
||||
edited_at timestamp,
|
||||
editor int(3),
|
||||
content varchar(255) NOT NULL,
|
||||
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
|
||||
|
||||
$db = static::connectDB();
|
||||
$query = $db->prepare($sql);
|
||||
|
||||
if ($query->execute()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function dropTable()
|
||||
{
|
||||
$sql = "DROP TABLE IF EXISTS pengumuman";
|
||||
|
||||
$db = static::connectDB();
|
||||
$query = $db->prepare($sql);
|
||||
|
||||
if ($query->execute()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
18
_tests/unit/ModelTest.php
Normal file
18
_tests/unit/ModelTest.php
Normal file
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
namespace Core;
|
||||
|
||||
// use Model;
|
||||
|
||||
class ModelTest extends \PHPUnit\Framework\TestCase
|
||||
{
|
||||
/**
|
||||
*
|
||||
* @test
|
||||
*/
|
||||
public function createNewTableWorkSuccess()
|
||||
{
|
||||
$model = new Model();
|
||||
$this->assertTrue($model->createTable());
|
||||
$this->assertTrue($model->dropTable());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user