This is maybe discussed several times but I want to know how OOP can help me improve my code. I used to code in procedural way. However with a reasonable logic. The pieces of code that are used all over the project are wrapped in functions. however all functions are put in a large functions.php file (which I find not very efficient). for example, this is a function to check if a sales is expired or not :
function is_sales_expired($salesId, PDO $conn) {
$now=time();
$sql="SELECT * FROM specialoffers WHERE id=:id";
$st=$conn->prepare($sql);
$st->bindvalue(":id",$salesId,PDO::PARAM_STR);
$st->execute();
$sales_array=$st->fetchAll();
if($now<$sales_array[0]['finishdate'] && $now>$sales_array[0]['startdate']) {
return FALSE;
} else {
return TRUE;
}
}
Now Ive decided to move to OOP and convert my code to OOP. So I created classes and put the functions related to a particular behavior into each class. for example a sales class which has a is_sales_expired()
and other methods related to sales. the properties and the constructor look like this :
class Sales
{
private $conn;
private $stockObj;
private $userObj;
private $cartObj;
private $randomObj;
function __construct(PDO $conn)
{
$this->conn = $conn;
$this->stockObj = new Stock($this->conn);
$this->userObj = new User($this->conn);
$this->cartObj = new Cart($this->conn);
$this->randomObj = new Random($this->conn);
}
//methods come here//
}
And then I load the classes in my code using spl_autoload_register
so I don't have to include all class files in every other file. Well with this approach, calling methods is a bit easier and I don't need to pass PDO $conn
to every method call and it is already passed with the constructor.
Well, these are all good and all related codes are now in one place and maybe a bit easier to manage. But I have a feeling that the OOP should have much more to offer. with the Approach that I used, I don't feel, that now my code is more efficient and maintainable. I feel I should have missed some concepts here. your help is appreciated.