Skip to content

Instantly share code, notes, and snippets.

@mike-gusiev
Last active August 29, 2015 14:20
Show Gist options
  • Save mike-gusiev/dda109f26d9b9b4996b2 to your computer and use it in GitHub Desktop.
Save mike-gusiev/dda109f26d9b9b4996b2 to your computer and use it in GitHub Desktop.
PHP tips
<?php
class MyApp {
private $DBH, $db = Array(
"type" => "mysql",
"host" => "localhost",
"db" => "spendmoney",
"user" => "spendmoney",
"pass" => "123456",
);
private function db_connect() {
try {
$this->DBH = new PDO(
$this->db["type"].":host=".$this->db["host"].";dbname=".
$this->db["db"]."", $this->db["user"], $this->db["pass"]
);
} catch(PDOException $e) {
file_put_contents("PDOErrors.txt", $e->getMessage(), FILE_APPEND);
return false;
}
return true;
}
private function db_get($query) {
if(!$this->DBH && !$this->db_connect()) return false;
try {
$STH = $this->DBH->query($query);
$STH->setFetchMode(PDO::FETCH_OBJ);
$data = Array();
while($row = $STH->fetch()) {
$data[] = $row;
}
return $data;
} catch(PDOException $e) {
file_put_contents("PDOErrors.txt", $e->getMessage(), FILE_APPEND);
return false;
}
}
private function db_execute($query) {
if(!$this->DBH && !$this->db_connect()) return false;
try {
$this->DBH->prepare($query)->execute();
if($id = $this->DBH->lastInsertId()) return $id;
return true;
} catch(PDOException $e) {
file_put_contents("PDOErrors.txt", $e->getMessage(), FILE_APPEND);
return false;
}
}
public function init() {
// $this->db_execute("INSERT INTO spend (amount, category) VALUES (20, 'food')");
$data = $this->db_get('SELECT * FROM spend');
echo '<pre>' . print_r($data, true) . '</pre>';
}
}
$myapp = new MyApp();
$myapp->init();
<?php
class GlobalStorage {
protected $data;
protected static $instance;
public static function singleton() {
if (self::$instance === null)
self::$instance = new self();
return self::$instance;
}
public static function set($key, $data) {
$ins = self::singleton();
$ins->data[$key] = $data;
}
public static function get($key) {
$ins = self::singleton();
if (isset($ins->data[$key]))
return $ins->data[$key];
return null;
}
protected function __construct() {
$this->data = array();
}
protected function __wakeup() {
}
protected function __clone() {
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment