Skip to content

Instantly share code, notes, and snippets.

@kinncj
Created May 10, 2013 00:08
Show Gist options
  • Save kinncj/5551558 to your computer and use it in GitHub Desktop.
Save kinncj/5551558 to your computer and use it in GitHub Desktop.
PDO and it's magics - PHP Brasil - May 9, 2013
{"driver":"mysql","server":"localhost","database":"pdoteste","username":"user","password":"password"}
<?php
class Db
{
private $pdo;
protected $table;
public function __construct()
{
$parameters = json_decode(file_get_contents('config.json'));
$dsn = "{$parameters->driver}:host={$parameters->server};dbname={$parameters->database}";
$this->pdo = new PDO($dsn, $parameters->username, $parameters->password, array(PDO::ATTR_PERSISTENT => true));
}
/**
* Cria a query
*
* @param array $fieldsParameter Array de parametros array("nome", "idade");
* @param array $whereParameter Array de parametros para cláusula where array(":nome"=>"xuplau")
*/
public function query(array $fieldsParameter = array('*'), array $whereParameter = array())
{
$rawQuery = "SELECT %FIELDS% FROM {$this->table} %WHERE%";
$fields = null;
$where = null;
foreach ($fieldsParameter as $field) {
$fields .= "{$field},";
}
$fields = substr($fields, 0, -1);
foreach ($whereParameter as $bind=>$value) {
$field = substr($bind, 1);
$where .= " {$field} = {$bind} AND";
}
if ( ! is_null($where)) {
$where = strpos("WHERE {$where}",0 -3);
}
$query = str_replace(array("%FIELDS%", "%WHERE%"), array($fields, $where), $rawQuery);
$statement = $this->pdo->prepare($query);
$statement->execute($whereParameter);
return $statement;
}
}
<?php
spl_autoload_register(function($class){
require_once "{$class}.php";
});
$UserDao = new UserDao();
$userList = $UserDao->findAll();
foreach ($userList as $user) {
$user->falarNome().PHP_EOL;
}
CREATE DATABASE pdoteste;
USE pdoteste;
CREATE TABLE users(id int autoincrement NOT NULL, nome text);
INSET INTO users(nome) VALUES("Foo"),("Bar"),("Baz");
<?php
class User
{
private $name;
public function falarNome()
{
echo "Ola, sou o {$this->nome}";
}
}
<?php
class UserDao extends Db
{
protected $table = 'users';
public function findAll()
{
$result = $this->query();
$userList = array();
while($user = $result->fetchObject("User")) {
$userList[] = $user;
}
return $userList;
}
}
@kinncj
Copy link
Author

kinncj commented May 10, 2013

E na real, o UserDao.php ta mais para um repository, sei la

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment