r/PHPhelp • u/Malaiac • Feb 01 '18
Am I doing OOP the wrong way ?
Ok, so I've been coding for a few years now, but I have a bias. I code mostly alone, delivering packaged scripts to customers, whether in vanilla PHP/MySQL (+some kind of a front but not always) or as a Prestashop/OpenCart/WordPress plugin.
I recently coded a scraping script : getting listings + ads every day, geo matching them and mailing them to the relevant targets, and I used the opportunity to upgrade my "not a framework more a set of functions organized in objects, like a HTTP object and a Text Object and a bare controller", and while browsing some tutorials and references, I once again asked myself if i was doing OOP The Right Way (spoiler : I'm not, but I'm willing to improve).
Brief view of the index.php code to have an actual example :
$Main = new MainSortOfAController(); // on construct : parse query, set up $Main->db = new DB() and $Main->http = new HTTP()
$Listings = new SourceListingsClass(); // class SourceListingClass (specific to the source of data) extends ListingClass
$Ads = new SourceAdsClass(); // idem
// sample action
$Listings->fetch_listings();The Listings Class has methods like fetch_listings(), parse_listings(), etc.
Classes usually stores non writable data in $this->data (with setData($id,$value) - conditional on $this->data[$id] being not set before, and getData()) and stores loop data (rewritten at each iteration) in $this->current (with setCurrent() and getCurrent, etc.)
In other words, I might be using objects as (very fat) controllers everytime and not as proper objects. I don't have any Listing class, or Ad class, but Ads class that fetch, parse and store data in loops.
I am interested in feedback, since I need to improve the maintainability and readability of my code, and am interested in changing the way I code, and maybe follow a mini framework project.
Performance is actually pretty good, all SQL statements are prepared in the DB class, HTML is in the /templates/ directory (ie be gentle with me)
Sidenote : plenty of websites/tutorials/books to explain the "how ?", very few if any to explain the "why ?". Design choices, script architecture, etc.
1
u/[deleted] Feb 01 '18
There are resources out there that explain the "why" and go into architectural/design choices. Try picking up a copy of a book like "Head First Design Patterns". "Patterns of Enterprise Application Architecture" is another well regarded one, but to be honest it's about as interesting to read as the title makes it sound.
Googling "design patterns" and reading around the results there should help you out too. From what you've written, I think something like the Repository patten could be a good start.