Global Rationality
Global Rationality

Reputation: 145

Is it best practice to put all PHP functions in separate files if you want to use them in combination with jQuery (Ajax) and get responses?

I normally put all functions in separate files, but I'm imagining ways to put everything in one file.

You could probably send the name of the needed PHP function along with each ajax-call and write something like the following in the PHP-file:

if($_POST['function_name'] == 'myfunction'){
myfunction();
}

function myfunction()
{
echo 'This to be echoed.'
}

Somehow that feels wrong. So, what is your opinion? All functions in one file or all separated?

Upvotes: 1

Views: 824

Answers (2)

Derek
Derek

Reputation: 4751

It's generally good practice writing code that is reusable, easily testable, and more maintainable. Having all of your functions in one file may make sense if they are all part of the same class or trait; if they are simply globally defined functions you're probably better off putting them in their own file.

Most framework libraries have a router system that determines what function handles a given request. I suggest looking at how they do that, or simply using one of them. Symfony and Laravel all have a modularized system where you can use what you need. I think CakePHP v3 does too.

Also look into SOLID (single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion).

Upvotes: 1

Alfred Woo
Alfred Woo

Reputation: 716

If your project is really big and has lots of people engaged to the project, separating files for each functions would be a nice option to work together.

But if it's not the case like that, putting every functions in one file will make your project looks more simple and productive.

Please note that this is just my personal opinion.

Upvotes: 1

Related Questions