Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP includes vs OOP

I would like to have a reference for the pros and cons of using include files vs objects(classes) when developing PHP applications.

I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others.

A Simple Example:

Certain pages on my site are only accessible to logged in users. I have two options for implementation (there are others but let's limit it to these two)

  1. Create an authenticate.php file and include it on every page. It holds the logic for authentication.

  2. Create a user object, which has an authenticate function, reference the object for authentication on every page.

Edit I'd like to see some way weigh the benefits of one over the other. My current (and weak reasons) follow:

Includes - Sometimes a function is just easier/shorter/faster to call Objects - Grouping of functionality and properties leads for longer term maintenance.

Includes - Less code to write (no constructor, no class syntax) call me lazy but this is true.

Objects - Force formality and a single approach to functions and creation.

Includes - Easier for a novice to deal with Objects - Harder for novices, but frowned upon by professionals.

I look at these factors at the start of a project to decide if I want to do includes or objects. Those are a few pros and cons off the top of my head.

like image 325
Markus Avatar asked Aug 22 '08 14:08

Markus


1 Answers

These are not really opposite choices. You will have to include the checking code anyway. I read your question as procedural programming vs. OO programming.

Writing a few lines of code, or a function, and including it in your page header was how things were done in PHP3 or PHP4. It's simple, it works (that's how we did it in osCommerce, for example, an eCommerce PHP application).

But it's not easy to maintain and modify, as many developers can confirm.

In PHP5 you'd write a user object which will carry its own data and methods for authentication. Your code will be clearer and easier to maintain as everything having to do with users and authentication will be concentrated in a single place.

like image 90
Christian Lescuyer Avatar answered Sep 27 '22 17:09

Christian Lescuyer