Está en la página 1de 12

Database.

php

<?php

/**
* Created by PhpStorm.
* User: Vasq
* Date: 6/03/2017
* Time: 19:13
*/

namespace System;

use PDO;
USE PDOException;

cl ass Database
{
/**
* Application Object
* @var \System\Application
*/

pr i vat e $app;
/**
* PDO Connection
* @var \Pdo
*/
pr i vat e st at i c $connection;

/**
* Table Name
* @var string
*/
pr i vat e $table;

/**
* Bindings Container
* @var array
*/
pr i vat e $bindings = [];

/**
* Last Insert Id
* @var int
*/
pr i vat e $lastId;

/**
* Data Container
* @var array
*/
pr i vat e $data = [];

/**
* Wheres
* @var array
*/
pr i vat e $wheres = [];

/**
* Selects
* @var array
*/
pr i vat e $selects = [];

/**
* Limit
* @var int
*/
pr i vat e $limit;

/**
* Offset
* @var int
*/
pr i vat e $offset;

/**
* Total Rows
* @var int
*/
pr i vat e $rows = 0;

/**
* Joins
* @var array
*/
pr i vat e $joins = [];

/**
* Order By
* @var array
*/
pr i vat e $orderBy = [];

/**
* Database constructor.
* @par am Application $app
*/

publ i c f unct i on __construct(Application $app)


{
$this->app = $app;

i f (!$this->isConnected()) {
$this->connect();
}
}

/**
* Determine if there is any connecion to database
* @r et ur n bool
*/
pr i vat e f unct i on isConnected()
{
r et ur n st at i c::$connection i nst anceof PDO;
}

/**
* Connect To Database
* @r et ur n void
*/
pr i vat e f unct i on connect()
{
$connectionData = $this->app->file->call("Config.php");
extract($connectionData);
try {
st at i c::$connection = new PDO('mysql:host=' . $server . ';dbname=' . $dbname, $dbuser, $dbpass);
st at i c::$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
st at i c::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
st at i c::$connection->exec('SET NAMES utf8');
} cat ch (PDOException $e) {
di e($e->getMessage());
}

/**
* Get Database Connection Obkect PDO Object
* @r et ur n \PDO
*/

publ i c f unct i on connection()


{
r et ur n st at i c::$connection;
}

/**
* Set select clause
*
* @par am string $select
* @r et ur n $this
*/
publ i c f unct i on select($select)
{
$this->selects[] = $select;
r et ur n $this;
}

/**
* Set Join clause
*
* @par am string $join
* @r et ur n $this
*/

publ i c f unct i on join($join)


{
$this->joins[] = $join;
r et ur n $this;
}

/**
* Set the table name
*
* @par am string $table
* @r et ur n $this
*/
publ i c f unct i on table($table)
{
$this->table = $table;
r et ur n $this;
}

/**
* Set Limit and offset
*
* @par am int $limit
* @par am int $offset
* @r et ur n $this
*/

publ i c f unct i on limit($limit, $offset = 0)


{
$this->limit = $limit;
$this->offset = $offset;
r et ur n $this;
}

/**
* Ftech Table
* This will return only one record
*
* @par am string $table
* @r et ur n \stdClass / null
*/

publ i c f unct i on fetch($table = null)


{
i f ($table){
$this->table($table);
}

$sql = $this->fetchStatement();
$result = $this->query($sql,$this->bindings)->fetch();
r et ur n $result;
}

/**
* Fetch ALL Records from TABLE
* This will return only one record
*
* @par am string $table
* @r et ur n array
*/
publ i c f unct i on fetchAll($table = null)
{
i f ($table){
$this->table($table);
}

$sql = $this->fetchStatement();
$query = $this->query($sql,$this->bindings);
$results = $query->fetchAll();
$this->rows = $query->rowCount();
r et ur n $results;
}

/**
* Get total rows from Last fetch all statement
* @r et ur n int
*/
publ i c f unct i on rows()
{
r et ur n $this->rows;
}

/**
* Prepare Select statement
* @r et ur n string
*/

pr i vat e f unct i on fetchStatement()


{
$sql = 'SELECT';
i f ($this->selects){
$sql .= implode(',', $this->selects);
}el se{
$sql .= '*';
}

$sql .= ' FROM ' . $this->table. ' ';

i f ($this->joins){
$sql .= implode(' ' , $this->joins);
}

i f ($this->wheres){
$sql .= ' WHERE '. implode(' ', $this->wheres). ' ';
}

i f ($this->limit){
$sql .= ' LIMIT '. $this->limit;
}

i f ($this->offset){
$sql .= ' OFFSET'. $this->offset;
}

i f ($this->orderBy){
$sql .= ' ORDER BY '. implode(' ',$this->orderBy);
}

r et ur n $sql;
}

/**
* Set Order By clause
*
* @par am string $column
* @par am string $sort
* @r et ur n $this
*/

publ i c f unct i on orderBy($orderBy, $sort = 'ASC')


{
$this->orderBy = [$orderBy, $sort];
r et ur n $this;
}
/**
* Set the table name
*
* @par am string $table
* @r et ur n $this
*/
publ i c f unct i on from($table)
{
r et ur n $this->table($table);
}

/**
* Set the Data that will be stored in database table
* @par am mixed $key
* @par am mixed $value
* @r et ur n $this
*/

/*
$this->db->data([
'name' => 'Ricardo',
'apellido' => 'vasquez'
]);
or
$this->db->data('name','Ricardo')->data('apellido','vasquez');
*/

publ i c f unct i on data($key, $value = null)


{
i f (is_array($key)) {
$this->data = array_merge($this->data, $key); //si es array agrega todos los valores a data
$this->addToBindings($key);

} el se {
$this->data[$key] = $value;
$this->addToBindings($value);
}
r et ur n $this;
}

/**
* Insert Data to database
*
* @par am string $table
* @r et ur n $this
*
*/
publ i c f unct i on insert($table = null)
{
i f ($table) {
$this->table($table);
}
$sql = 'INSERT INTO ' . $this->table . ' SET ';
$sql .= $this->setFields();
$this->query($sql, $this->bindings);
$this->lastId = $this->connection()->lastInsertId();
r et ur n $this;
}

/**
* Update Data in database
*
* @par am string $table
* @r et ur n $this
*
*/
publ i c f unct i on update($table = null)
{
i f ($table) {
$this->table($table);
}
$sql = 'UPDATE ' . $this->table . ' SET ';

$sql .= $this->setFields();
i f ($this->wheres){
$sql .= ' WHERE ' . implode('' , $this->wheres);
}
$this->query($sql, $this->bindings);
r et ur n $this;
}

/**
* Delete Clause
*
* @par am string $table
* @r et ur n $this
*
*/
publ i c f unct i on delete($table = null)
{
i f ($table) {
$this->table($table);
}
$sql = 'DELETE FROM ' . $this->table . ' ';

i f ($this->wheres){
$sql .= ' WHERE ' . implode('' , $this->wheres);
}
$this->query($sql, $this->bindings);
r et ur n $this;
}

/**
* Set the fields for insert and update
* @r et ur n string
*/
pr i vat e f unct i on setFields()
{
$sql = '';
f or each (array_keys($this->data) as $key) {
$sql .= '`' . $key . '` = ? , ';
}

$sql = rtrim($sql, ', ');


r et ur n $sql;

/**
* Add New Where clause
* @r et ur n $this
*/

publ i c f unct i on where()


{
$bindings = func_get_args();
$sql = array_shift($bindings);
$this->addToBindings($bindings);
$this->wheres[] = $sql;
r et ur n $this;
}

/**
* Execute the given sql statement
* @r et ur n \PDOStatement
*/
publ i c f unct i on query()
{
$bindings = func_get_args();
$sql = array_shift($bindings);

i f (count($bindings) == 1 AND is_array($bindings[0])) {


$bindings = $bindings[0];
}

try {
$query = $this->connection()->prepare($sql);

f or each ($bindings as $key => $value) {


$query->bindValue($key + 1, _e($value));
}
$query->execute();
$this->reset();

r et ur n $query;
} cat ch (PDOException $e) {

echo $e->getMessage();
}
}

pr i vat e f unct i on reset(){

//$this->rows = 0;
$this->limit = null;
$this->offset = null;
$this->table = null;
$this->bindings = [];
$this->data = [];
$this->selects = [];
$this->joins = [];
$this->wheres = [];
$this->orderBy = [];
}

/**
* Get the las insert id
* @r et ur n int
*/
publ i c f unct i on lastId()
{
r et ur n $this->lastId;
}

/**
* Add the given value to bindings
* @par am midex $value
* @r et ur n void
*
*/
pr i vat e f unct i on addToBindings($value)
{
i f (is_array($value)){
$this->bindings = array_merge($this->bindings,array_values($value));
}el se{
$this->bindings[] = $value;
}

}
Loader.php

<?php

/**
* Created by PhpStorm.
* User: Vasq
* Date: 6/03/2017
* Time: 10:56
*/

namespace System;

cl ass Loader
{
pr i vat e $app;
pr i vat e $controllers = [];
pr i vat e $models= [];

publ i c f unct i on __construct(Application $app)


{
$this->app = $app;
}

publ i c f unct i on action($controller, $method, $arguments = [])


{
$objController = $this->controller($controller);
call_user_func([$objController,$method],$arguments);

publ i c f unct i on controller($controller)


{
$controllerName = $this->getNameController($controller);
i f (!$this->hasController($controllerName)) {
$this->addController($controllerName);
}
r et ur n $this->getController($controllerName);
}

pr i vat e f unct i on getNameController($controller)


{
$controller .="Controller";
$controllerName = "App\\Controllers\\" . $controller;
r et ur n str_replace("/", "\\", $controllerName);
}

pr i vat e f unct i on hasController($controllerName)


{
r et ur n i sset ($this->controllers[$controllerName]);

pr i vat e f unct i on addController($controllerName)


{
i f ($this->app->file->exists($controllerName.'.php')){
$objController = new $controllerName($this->app);
$this->controllers[$controllerName] = $objController;
}el se{
di e("No se encontro el controlador solicitado");
}
}

pr i vat e f unct i on getController($controllerName)


{
r et ur n $this->controllers[$controllerName];
}

publ i c f unct i on model($model)


{
$modelName = $this->getNamemodel($model);
i f (!$this->hasmodel($modelName)) {
$this->addmodel($modelName);
}
r et ur n $this->getmodel($modelName);
}

pr i vat e f unct i on getNamemodel($model)


{
$model .="model";
$modelName = "App\\models\\" . $model;
r et ur n str_replace("/", "\\", $modelName);
}

pr i vat e f unct i on hasmodel($modelName)


{
r et ur n i sset ($this->models[$modelName]);

pr i vat e f unct i on addmodel($modelName)


{
i f ($this->app->file->exists($modelName.'.php')){
$objmodel = new $modelName($this->app);
$this->models[$modelName] = $objmodel;
}el se{
di e("No se encontro el modelo solicitado");
}
}

pr i vat e f unct i on getmodel($modelName)


{
r et ur n $this->models[$modelName];
}

}
Model.php

<?php

/**
* Created by PhpStorm.
* User: Vasq
* Date: 6/03/2017
* Time: 11:33
*/

namespace System;

abst r act cl ass Model


{
pr ot ect ed $app;

pr ot ect ed $table;
publ i c f unct i on __construct(Application $app)
{
$this->app= $app;
}
publ i c f unct i on __get($key)
{
r et ur n $this->app->get($key);

/**
* Call Database methods dynamically
*
* @par am string
* @par am array $args
* @r et ur n mixed
*
*/

publ i c f unct i on __call($method, $args)


{
r et ur n call_user_func_array([$this->app->db,$method],$args);
}

/*
* Get all Model Records
* @return array
*/

publ i c f unct i on all()


{
r et ur n $this->fetchAll($this->table);
}

/**
* Get Record By Id
*
* @par am int $id
* @r et ur n \stdClass /null
*/
publ i c f unct i on get($id)
{
r et ur n $this->where('id = ?',$id)->fetch($this->table);
}
}
UsersModel.php

<?php

/**
* Created by PhpStorm.
* User: Vasq
* Date: 7/03/2017
* Time: 18:10
*/

namespace App\Models;

use System\Model;

cl ass UsersModel ext ends Model


{
/**
* Table name
* @var string
*/
pr ot ect ed $table = 'users';
}

También podría gustarte