Postingan lainnya
Chain method php
Sekarang saya lagi membuat project "QueryBuilder", fitur yang sama kek di laravel.
Ini file utamanya:
class Query extends DB {
private static $tb;
private $query_stmt;
private $key;
private $trigger_code;
public static function table(string $arg) {
self::$tb = $arg;
return new static;
}
public function select(array $column) {
$column_stmt = "";
if(is_array($column)) {
foreach($column as $q) {
if($q != $column[array_key_last($column)]) {
$column_stmt .= $q.",";
} else {
$column_stmt .= $q;
}
}
$this->query_stmt = "SELECT $column_stmt FROM ".self::$tb;
return $this;
}
}
public function where(array $arg) {
if(is_array($arg)) {
$this->key = $arg[array_key_first($arg)];
$this->query_stmt .= " WHERE ".array_key_first($arg). " = ?";
$this->trigger_code = 1;
return $this->exec();
}
}
public function like(array $arg) {
if(is_array($arg)) {
$this->key = $arg[array_key_first($arg)];
$this->query_stmt .= " WHERE ".array_key_first($arg). " LIKE ?";
$this->trigger_code = 2;
return $this->exec();
}
}
public function exec() {
$stmt = $this->koneksi->prepare($this->query_stmt);
if($this->trigger_code == 1) {
$stmt->execute([$this->key]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} else if($this->trigger_code == 2) {
$stmt->execute(["%".$this->key."%"]);
return $stmt->fetchall(PDO::FETCH_ASSOC);
}
}
}
Ini cara penggunaan, menggunakan select sekaligus where
$x = Query::table("dataapi")
->select(["id","username"])
->where(["username" => "ahmad"]);
print_r($x);
// Hasil nya berhasil
// Outputnya seperti ini
Array ( [id] => 29 [username] => Ahmad )
tapi, ketika saya menggunakan fitur select doang
$x = Query::table("dataapi")
->select(["id","username"]);
print_r($x);
Outputnya kaya gini:
Query Object ( [koneksi:protected] => PDO Object ( ) [query_stmt:Query:private] => SELECT id,username FROM dataapi [key:Query:private] => [trigger_code:Query:private] => )
Kenapa seperti itu ya?
ekspektasi saya sih, harusnya me-return hasil keseluruhan.
Maaf kepanjangan pertanyaannya, soalnya saya bingung mau nanya dimana lagi
1 Jawaban:
<div>Di method select dia masih return ke object itu sendiri, artinya yaa belum ada action apapun yg dijalanin, sedangkan di method where itu akan di lanjutkan ke method exec.<br>Kalo tujuan akhirnya mau muncul resultnya, tinggal gini aja :<br><br></div><pre>$x <strong>=</strong> Query<strong>::</strong>table("dataapi") <strong>-></strong>select(["id","username"])->exec();
print_r($x);</pre>
Tanggapan
Terima kasih atas jawabannya bng, sudah bisa skrg