I’m very new to PHP so far and have been trying to learn it. A big difficulty I face though is I just can’t bend my head around to think about how is a PHP website structured with classes, objects, namespaces.
I’m not entirely new to OOP as I do have a little experience in Python and Java but PHP OOP just got me stumped. Many of the newbie PHP books I saw were on procedural PHP. I followed them made 1–2 small website but when I got to OOP, I’m just stuck and any tips on how you made the transition from procedural to OO PHP would be appreciated. In particular these are the questions on my mind at this moment
- What are the type of classes one would usually creates? I thought of giving a class for each table in my database (User, Book) as well as maybe a form class, are there any other type of candidates that could be turned into classes too?
- Any other way to reduce html code duplication other than the old usual require() and include()?
- Any recommended ways to structure a typical PHP website? I currently only knows of having a folder for includes file. But I would like to know more.
Thanks.
You have questions, here are my answers!
The classes you make in PHP can be related to objects like User, Book as you would do in a persistent program. If you look at a framework like Code Igniter you can make a class as specific as constructing database queries to a class that uses an MVC architecture consisting of multiple classes to render your entire website.
To reduce code duplication, you can, for example, write a class to construct a table (or if you are really fancy a div table maker.). Then you can write methods like makeRow(), makeDivision(), etc… get really fancy and then you can write clean PHP code that can generate really large powerful pages.
EDIT:
If you were talking about reducing about the amount of include you’d have to do for classes then yes, Autoloading Classes on the PHP website is something you will want to look at!
Structure of your website can be based on the model you want to use. Right now it seems that MVC models are popular with frameworks, but it is up to you how your want your web app to be made. I’m sure you can take any architecture model and base your website around it.
With all that said, if you don’t feel like start from absolute scratch on your project there are a plethora of PHP frameworks to choose from:
Comparison of Web application frameworks: PHP via Wikipedia