I am developing a web application for my company. The application is used to keep track of the tools we buy (and use).
Each time a worker in the company is using a tool it is registered in the application (mysql db). Until now I have written the code in procedural style. Still a novice in OOP and my procedural code works fine and are relative fast.
Now the application is getting larger and I’m really having issues maintaining my old coding pattern, so I figured it was about time to move on and try implementing OOP. The problem I’m facing now is that I somehow made my classes in a way so the application is up to 10 times slower that before. One of my pages takes 1 sec to load - without the classes it takes 0.1 sec. I use php microtime to measure this.
I’ve created a Company class which holds the properties for each company. Snippet of the class:
class Company {
private $companyId;
private $name;
private $cvr;
etc…..
private $tools = array();
}
So far it’s working as expected. Now I wanted to create a method to get all the companytools and attach it to the $tools array.
public function tools() {
$purchases = $db
->table('CompanyTools')
->select(
'id'
)
->where('CompanyTools.companyId', '=', $this->companyId)
->get();
$objects = array();
foreach ($purchases as $purchase) {
$objects[] = new CompanyTool($purchase['id']);
}
$this->tools = $objects;
return $this->tools;
}
Now when I use it like this I get the performance issues mentioned ealier
foreach ($company->tools() as $purchase) {
echo $purchase->id;
}
I suspect it has something to do with the loop creating a new instance of the CompanyTool class. The CompanyTool class looks something like this
class CompanyTool {
function __construct($id = null) {
if(!$id) die("We need the id");
$this->id = $id;
$attributes = $db
->table('CompanyTools as ct')
->select(
'ct.*'
)
->where('ct.id', '=', $this->id)
->take(1)
->get();
foreach($attributes as $attribute)
foreach ($attribute as $key => $value) {
if(property_exists($this, $key)) $this->{$key} = $value;
}
return $this;
}
I hope it's obvious what I'm trying to achieve and my lack of OOP knowledge :)
Thanks for your input
/ j