Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Tips for PHP Function Include Files

Good design dictates only writing each function once. In PHP I'm doing this by using include files (like Utils.php and Authenticate.php), with the PHP command include_once. However I haven't been able to find any standards or best practices for PHP include files. What would you at StackOverflow suggest?

I'm looking for:

  • Naming Standards
  • Code Standards
  • Design Patterns
  • Suggestions for defining return types of common functions (now I'm just using associative arrays).
like image 923
C. Ross Avatar asked Dec 17 '22 09:12

C. Ross


2 Answers

One convention I like to use is to put each class in its own file named ClassName.class.php and then set up the autoloader to include the class files. Or sometimes I'll put them all in a classes/ subdirectory and just name them ClassName.php. Depends on how many class vs. non-class includes I'm expecting.

If you organize your utility functions into classes and make them static methods instead, you can get away with writing only a single require_once() in your top level files. This approach may or may not be appropriate for your code or coding style.

As for return types, I try to follow the conventions used in the built-in functions. Return a type appropriate to the request, or return false on failure. Just make sure you use the === operator when checking for false in the results.

The fact that you're concerned about conventions suggests you're already on the right track. If you are familiar with any other OOP language like Java, C++, C#, etc., then you'll find you can follow a lot of the same conventions thanks to the OOP goodness in PHP5.

like image 101
Ryan Graham Avatar answered Jan 04 '23 08:01

Ryan Graham


Whatever naming convention you end up using (I prefer to take cues from either Java or C# wherever possible) make sure if you use include files for functions that they do not actually execute any code upon including, and never include the same file twice. (use include-once or require-once)

like image 26
Kris Avatar answered Jan 04 '23 09:01

Kris