Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize PHP code?

Tags:

php

I'm writing an app in modular way, so I can possibly reuse some of the components. I've also written utility functions that are shared among different components. For example, if I have classes A (in A.php), B (in B.php), and C (in C.php), and a function f (in utils.php), and this function is used in both A, B, and C, how does one organize the code?

For testing purposes, I run A.php, B.php, and C.php separately, so I need to include utils.php in all of them. Is doing require_once 'utils.php' in all three files a good solution? I've heard there may be a minor performance issue with using require_once. Or should I maybe write a separate 'test.php', whre I would import all the files I need, and use that code for testing instead of writing tests in actual class files?


2 Answers

First of all, require_once is certainly not "too" slow for running your tests. Remember, premature optimization is the root of all evil. Yes, it has some overhead, but unless it causes errors or slows down your production environment, don't bother. Measure, measure measure.

A good strategy that i tend to use is similar to the one of Zend Framework.

My classnames are based on my directory structure. For example, a class named Http_Client_Curl would be lokated in the following directory:

Http/Client/Curl.php

With a structure like this, it's very easy and convenient to use auto loading. See spl_autoload_register. This means that you can let PHP automatically include all files and classes as you need them, based on a pretty straight forward convention.

like image 65
alexn Avatar answered Nov 23 '25 09:11

alexn


If you are speaking in terms of PHP 5.3, I believe namespaces and auto-loading would fit right into your application fairly well. On the other hand, legacy code tends to be organized into "libraries" or "includes" with a core "includes.inc.php" that uses the factory method, or various other design pattern, to load the classes.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!