From 031a188f5bb61a98e0f8ddb40395e83583a6bdf8 Mon Sep 17 00:00:00 2001 From: Gregorio Chiko Putra Date: Thu, 31 Aug 2017 15:09:43 +0700 Subject: [PATCH] Make a better database interactions --- App/Models/Post.php | 13 +++++++------ Core/Model.php | 12 +++++------- _tests/unit/PostTest.php | 17 ++++++++++++----- 3 files changed, 24 insertions(+), 18 deletions(-) diff --git a/App/Models/Post.php b/App/Models/Post.php index 2f6418a..3594b38 100644 --- a/App/Models/Post.php +++ b/App/Models/Post.php @@ -30,6 +30,7 @@ class Post extends \Core\Model if ($stmt = $db->query($sql)) { $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); + // For tests return true; } return false; @@ -60,16 +61,16 @@ class Post extends \Core\Model } } - public function entry($fields, $vals) + public function entry($args) { - if (count($fields) && count($vals) && count($fields) === count($vals)) { - $keys = '`'.implode('`, `', $fields).'`'; + if (count($args)) { + $keys = '`'.implode('`, `', array_keys($args)).'`'; $x = 1; $values = ''; - foreach ($vals as $val) { + foreach ($args as $field) { $values .= '?'; - if ($x < count($vals)) { + if ($x < count($args)) { $values .= ', '; } $x++; @@ -84,7 +85,7 @@ class Post extends \Core\Model $x = 1; - foreach ($vals as $val) { + foreach ($args as $val) { $query->bindValue($x, urldecode($val)); $x++; } diff --git a/Core/Model.php b/Core/Model.php index 30c06d6..360b2ab 100644 --- a/Core/Model.php +++ b/Core/Model.php @@ -5,20 +5,18 @@ use App\Config; abstract class Model { - protected static $dsn; + protected static $conn = null; protected static function connectDB() { - static $conn = null; - try { - if (!$conn) { + if (!self::$conn) { $dsn = 'mysql:host='.Config::DB_HOST.';dbname='.Config::DB_DB; - $conn = new \PDO($dsn, Config::DB_UNAME, Config::DB_PWD); + self::$conn = new \PDO($dsn, Config::DB_UNAME, Config::DB_PWD); - $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + self::$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } - return $conn; + return self::$conn; } catch (PDOException $e) { echo $e->getMessage(); } diff --git a/_tests/unit/PostTest.php b/_tests/unit/PostTest.php index ccaa1af..8a3bd07 100644 --- a/_tests/unit/PostTest.php +++ b/_tests/unit/PostTest.php @@ -7,18 +7,25 @@ class PostTest extends \PHPUnit\Framework\TestCase * * @test */ - public function showDataSuccess() + public function databaseInteractionsSuccess() { $post = new Post(); $this->assertTrue($post->showAll()); - $fields = ['category', 'expired_at', 'creator', 'content']; - $values = ['3', '2017-09-02', '2', 'barbarbarbarbarbarbar!']; + $args = [ + 'category' => 3, + 'expired_at' => '2017-09-02', + 'creator' => 2, + 'content' => 'barbarbarbarbarbarbar!' + ]; - $this->assertTrue($post->entry($fields, $values)); + $this->assertTrue($post->entry($args)); - $args = ['category' => 5, 'content' => 'foofoofoofoo!']; + $args = [ + 'category' => 5, + 'content' => 'foofoofoofoo!' + ]; $this->assertTrue($post->update($args, 1));