PHP - Split code into multiple files or keep it in as few files as possible?

7.4k views Asked by At

Right now I have a script that has reached 400 KB in 4 files (about 3500 lines per file).

Should I split it into more files?

Does having more files have a impact on performance because of multiple require_once calls?

5

There are 5 answers

0
Andrew On BEST ANSWER

I have a large, 13000 line script that I combined from three others, but it's entirely view and user-management related, dealing with output and receiving input. The functions are in another, 8000 line file, and I make sure there's zero bleedover between the two. No HTML in the functions file, no SQL in the main file. Would this be different if I could use objects? Of course. Can't.

So the moral of the story is: It all depends on what makes you comfortable for the script in question. I have one other that is 5 small files because it makes more sense that way; this one makes sense as two large ones.

0
Michael Irigoyen On

When using require or include, PHP processes all the files as if it was one big file (imagine copy and pasting the code from the included files into your master file).

The only thing you'd really gain from splitting into separate files is organization. Organization can be huge when working with that much code, so it really depends on what works the best for you.

0
profitphp On

The impact will be negligible. You'll get way more bang for your optimization buck speeding up database queries etc. Include or require is slightly faster than require_once though, as it doesn't have to check if its already been included before hand.

So to answer the question, "should you split it into more files?". Sure, if it will keep it cleaner go ahead.

0
Matt On

Split related lines into functions. Group related functions and data into classes. If you aren't thinking about how you organize your code as you write it, you are creating more work for someone else, or yourself, down the road.

0
Dean Rather On

Hardware is cheap, Programmers are expensive. as profitphp said, the performance hit is negligable. What's a bigger waste of resources in the long run? the complexity of working in a tens of thousands of lines of code file, or the microsecond load time you'll save?

I don't know your motives, but if reorganising your code will put you in a comfortable environment, go for it! Be careful when refactoring though, don't bite off more than you can chew. And use source control.