-1

I am currently writing a PHP / JavaScript application library, which I intend to use in the future for several other applications. The library includes functionality for handling a database, creating users / hashing and checking passwords, etc.

I am wondering whether there are any accepted best practices on how to organise PHP code in files, etc.? I have recently transitioned from C++ where I was quite content with the way I ordered my code, but since finding out PHP doesn't do the whole "header file" "content file" thing, I am left wondering whether there are any guidelines I should follow for clarity's sake. I am currently including all method definitions within the one class file, which feels messy and inelegant to me.

How do people do this? Separate methods into traits? Separate files for each methods? All the methods in one file but separate from class definition? Or just dump it all in the class declaration file?

Any imput on this (or any other code organisation best practices) much appreciated!

asked Feb 5, 2024 at 20:19
1
  • 1
    If this isn't just a learning exercise (and maybe even if it is) make sure you're not wastefully duplicating functionality that's already freely available in the PHP platform or ecosystem. For instance PHP has good password functions built-in: password_hash and password_verify. Commented Feb 5, 2024 at 20:54

1 Answer 1

1

The standard is one file per class or class-like (i.e. class, interface, trait or enum)

Following this standard fits with use of PSR-4 autoloading standard and the near ubiquitous Composer autoloader. If each class-like symbol is in its own file, with a name and path that's predictable based on the name of the symbol, then the autoloader can automatically load the file only when needed.

Traits are not generally used just to separate out methods - they tend to be used as a way to provide code re-use by some developers, and avoided by others.

PSR-1 is an optional but widely followed set of rules about how to write PHP files.

answered Feb 5, 2024 at 20:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.