Simple Rules to Keep a PHP Codebase Organized

PHPweb-development

I'm new to PHP in a professional context. I want a few macro thumb rules to keep me on the enlightened path. Here are a few I'm proposing to myself:

  • no absolute paths in include|require(_once)? statements
  • no .. dirname(foo), or other means of walking up in include|require(_once)? statements
  • put libs on the include path, not in subdirectories

You can see that all of this is focusing on managing dependencies, because that is the problem I've encountered thus far.

What other thumb-rule solutions to macro level problems do you have?

Best Answer

Without a little more context it's hard to suggest anything, but here are a few replies to your points you've made:

Dependencies - use Composer to manage your dependencies. It'll dump them into vendor (configurable) and you'll be able to easily upgrade them or add new ones. Don't use the include path unless its truly system wide stuff (such as phpunit). If you have multiple apps on the same server, they may require different versions of libraries.

Relative Paths - use them where they make sense. If your package is to be portable, it makes more sense to use relative paths. __DIR__.'/some_subdirectory' is quite common and typically recommended for portability. It really depends on what you are using it for though.

Loading Classes - the PHP community has widely adopted autoloading. Composer will do this for you, but typically you see classes mapped to the filesystem

Company/Package/ClassName is located in src/Company/Package/ClassName.php (or that same Company/... structure inside a vendor directory).

Check out a new set of tutorials / guides called PHP: The Right Way which is trying to organize all these things into a large reference. If you want the latest from the professional community, that's the place to check. The web is littered with bad advice, so tread carefully!

Related Topic