Selamün Aleyküm herkese,
Php yeteneklerimizi geliştirirken bu MVC'deki model nasıl çalışır merak etmiştim. Aynı laraveldeki gibi ama onun kadar gelişik olmayan bir o kadar da hatası bulunan örneğimi sizinle paylaşmak isterim. 🙂
Saygılar.
Edit 1 : Konu etiketi yalnış seçmişim üstatlar düzeltirlerse sevinirim biz yapamıyoruz herhalde.
Class => DB.php
<?php
namespace app\classes;
use PDO;
use PDOException;
class DB
{
private $databaseConnectionMaterials = [];
private $db;
public function __construct()
{
$this->databaseConnectionMaterials = require __DIR__.'/../config/database.php';
}
public function connection() : PDO
{
$host = $this->databaseConnectionMaterials['DB']['host'];
$dbname = $this->databaseConnectionMaterials['DB']['dbname'];
$port = $this->databaseConnectionMaterials['DB']['port'];
$user = $this->databaseConnectionMaterials['DB']['user'];
$pass = $this->databaseConnectionMaterials['DB']['pass'];
try{
$this->db = new PDO("mysql:host=$host;dbname=$dbname;port=$port",$user,$pass);
return $this->db;
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
public function __destruct()
{
$this->db = null;
}
}
Class => Model.php
<?php
namespace app\classes;
use PDO;
class Model
{
private string $className;
private array $columns = [];
private int $limit=0;
public function __construct()
{
$explodedData = explode('\\',get_class($this));
$this->className = strtolower(end($explodedData));
}
public function select(array $columns) : Model
{
$this->columns = $columns;
return $this;
}
public function limit(int $limit) : Model
{
$this->limit = $limit;
return $this;
}
public function get() : string
{
if(count($this->columns) > 0)
{
foreach ($this->columns as $column){
$columns .= '`'.$column.'`,';
}
$columns = substr($columns,0,-1);
$sqlString = "SELECT $columns FROM $this->className";
}
else
{
$sqlString = "SELECT * FROM $this->className";
}
if($this->limit !== 0)
{
$sqlString .= " LIMIT ".$this->limit;
}
echo "$sqlString";
$db = new DB();
$statement = $db->connection();
$statement = $statement->prepare($sqlString);
$statement->execute();
return json_encode($statement->fetchAll(PDO::FETCH_ASSOC));
}
}
Model => Class => Product.php
<?php
namespace app\models;
use app\classes\Model;
class Products extends Model
{
}
Model => Class => Categories.php
<?php
namespace app\models;
use app\classes\Model;
class Categories extends Model
{
}
public => index.php
<?php
require_once '../app/autoload.php';
use app\models\Categories;
use app\models\Products;
$products = new Products();
$categories = new Categories();
print_r($products->limit(2)->select(['name'])->get());
echo "<hr>";
print_r($categories->select(['name','description'])->limit(2)->get());