All of the codes are based on the PSR-2 standard. Also Dependency-Injection and Repository patterns are followed. I would love to hear some advices or comments.
StudentRepository Class
namespace REST;
use Slim\PDO\Database;
interface IStudentRepository
{
//Functions to be defined
public function __construct();
public function getStudentNames($request, $response, array $args);
public function getAll($request, $response, array $args);
public function addStudent($name, $id);
public function updateName($id, $new_name);
}
class StudentRepository implements IStudentRepository
{
//Queries and MYSQL connection
protected $pdo;
public function __construct()
{
//Database connection
$dsn = 'mysql:host=localhost;dbname=College_DB;charset=utf8';
$usr = 'root';
$pwd = '';
$this->pdo = new \Slim\PDO\Database($dsn, $usr, $pwd);
}
public function getStudentNames($request, $response, array $args)
{
$array_val = array();
$sql = 'SELECT name FROM Students';
$cntrl=0;
foreach ($this->pdo->query($sql) as $row) {
$array_val[$cntrl]=$row["name"];
$cntrl++;
}
$n_response = $response->withJson($array_val, 200);
return $n_response;
}
public function getAll($request, $response, array $args)
{
$array_val = array();
$sql = 'SELECT * FROM Students';
foreach ($this->pdo->query($sql) as $row) {
$array_val[$row["id"]]=$row["name"];
}
$n_response = $response->withJson($array_val, 200);
return $n_response;
}
public function addStudent($id, $name)
{
$stmt = $this->pdo->prepare('INSERT into Students(id,name) values(:id,:namee)');
$stmt->bindParam(":id", $id, \Slim\PDO\Database::PARAM_STR);
$stmt->bindParam(":namee", $name, \Slim\PDO\Database::PARAM_STR);
$stmt->execute();
}
public function updateName($id, $new_name)
{
$stmt = $this->pdo->prepare('UPDATE Students set name=:namee where id=:id');
$stmt->bindParam(":id", $id, \Slim\PDO\Database::PARAM_STR);
$stmt->bindParam(":namee", $new_name, \Slim\PDO\Database::PARAM_STR);
$stmt->execute();
}
}
StudentController Class
<?php
namespace REST;
class StudentController
{
protected $Student_DB;
public function __construct(IStudentRepository $Student_DB)
{
$this->Student_DB=$Student_DB;
}
public function getStudents($request, $response, array $args)
{
return $this->Student_DB->getAll($request, $response, $args);
}
public function getStudentNames($request, $response, array $args)
{
return $this->Student_DB->getStudentNames($request, $response, $args);
}
public function addStudent($request, $response, array $args)
{
if (array_key_exists("id", $args) && array_key_exists("name", $args)) {
$id = $args["id"];
$name = $args["name"];
if (!is_numeric($id) || !ctype_alpha($name)) {
$n_response = $response->withStatus(400);
return $n_response;
}
}
$this->Student_DB->addStudent($id, $name);
$n_response = $response->withStatus(200);
return $n_response;
}
}
Edit : I have edited the code in order to return JSON data with spesific status codes.