francis
francis

Reputation: 307

how to manage includes and require_once in an effective way in php?

I have some defines in my index.php, with values pointing to some folders. I want to avoid the anoying requires:

require_once("something/../../../file.php")

The problem (because of the scope) is that Those defines are lost when I try to use them in another php file, then I need to make again require_once("/../../......etc"), or define them again.

How can I avoid this to have something like:

require_once(PATH_LIBRARY1."/my_file.php")?

Upvotes: 1

Views: 1347

Answers (3)

sectus
sectus

Reputation: 15464

  1. You must learn about autoloading. It helps to avoid of using require or include at all.

  2. About psr-0 standard. It helps manage your classes in file system correctly. And use simple autoload function.

  3. About composer. It helps to avoid writing of anything for autoloading. Even if you are not using psr-0 it can create class map.

Upvotes: 4

Sven
Sven

Reputation: 70863

In modern PHP applications the need for require/include is very small because the most effective way to include code is to use OOP classes and the autoload feature. That way you never have to worry where the code for any class is located, you simply use the class.

The only things that still need to be included manually are functions outside of classes and things like configuration arrays that also do not define a class themselves.

Upvotes: 2

helion3
helion3

Reputation: 37381

A few choices:

  • Use Autoloading
  • Define a base path constant for the application and rely on that
  • Define a central library that's responsible for loading the classes you need

Upvotes: 1

Related Questions