What is the best practice for including PHP files? [duplicate] - php

This question already has answers here:
PHP include best practices question
(10 answers)
Closed 9 years ago.
What is the best practice for including PHP files?
Is it best to include a include.php file that includes all of the project PHP files?
Or to include it in those files that need them
Right now, my project has several include files in my index.php file. Does including all of my php files in the index.php make it less efficient?
Lastly, Where should one include the session check PHP file? in all of the PHP files?

EDIT 2016
Well, 5 years since I replied this. I am still alive. A lot has changed.
Now I use autoloaders to include my files. Here is official info for autoloaders with examples.
Basically, the idea is to have a proper folder structure (PSR-4 standards for instance) and having a class within each file. This way you can use autoloaders and PHP will load your files automatically.
OLD ANSWER
Usually, I have a config file like this:
define(root, $_SERVER['DOCUMENT_ROOT']);
.... // other variables that are used a lot
include (root . '/class/database.php');
.... // other includes that are mostly called from each file, like a db class, or user class, functions etc etc...
if (defined('development'))
{
// turn error reporting on
}
else
{
// turn it off
}
etc etc... You got the point of config.
And I include the config.php on each file. I forgot how to do it right now, but apache can do the automatic include for you. Therefore, you can say to apache to include your config file by default.
Then, I have controller classes, which call the views. There in each function I call the view.
someController.php
function index() { include root . '/views/view_index.php'; }
finally, from the view, if I need to include the header and footer view I do it like this:
view_index.php
<?include root . '/view/shared/header.php';?>
<div class="bla bla bla">bla bla bla</div>
<?include root . '/view/shared/footer.php';?>
I always use include in this structure rather than include_once since the latter requires extra check. I mean, since I am pretty sure that I include files only once, I don't need to use include_once. This way, you also know which include is where. For instance, you know that crucial files like db.php, or functions.php are located in config.php. Or you know that include views are located in controllers. That's pretty useful for me, I hope that helps you, too.

Using the include.php file is a very good practice according to me, as it is very helpful in changing the included files in big projects. If the project is small then including individual files is not a problem. But it becomes a problem to manage them as the project grows big.
For the session check file it is better to attach them individually as the requirement to check session on different pages might differ.
Including files individually or including them all in a single file and then including that makes much of the difference to the performance. As ultimately all the files are going to be included. It only becomes easy to manage them if single file is used to handle them.

I don't assume you are using object oriented programming but in case you do here might be a good answer.
In php you can define a function called the autoloader, if you try to create an object of a class that has not been defined the autoloader is called. You can then use the class name to figure out where the file containing that class is stored to include it at the last moment. Here is an example..
<?php
function on_load($class)
{
if(file_exists(require_once('classes/'.$class.'.php')))
{
require_once('classes/'.$class.'.php');
}
else
{
throw new Exception('Class not found: '.$class.' in classes/');
}
}
spl_autoload_register('on_load'); // tell php to call your on_load function if the class was not defined
If you're working on a big project you might want to group your files like this
/classes/database/MySQL.php
/classes/database/PDO.php // I'm just listing random stuff
/classes/Core.php // Whatever
/classes/datastructure/HashMap.php
You can then use a special naming convention to find the right directory
class Database_MySQL{} // look in <root_dir>/database/ for MySQL.php
class Core // look in <root_dir>/ for Core.php
class Database_Driver_Adapter_Useless_MysqlAdapterThingy {} // look in <root_dir>/Database/Driver/... blabla
Or you can use the php 5.3 way and define your classes like this
<?php
namespace database\driver\adapter\useless;
use database\driver\adapter\MysqlAdapter; // Now you have to tell PHP which version of MysqlAdapter class you want to use, even if there is just one
class MysqlAdapterThingy extends MysqlAdapter {}
Now you have to use the 'use' keyword in every file you need that class. The cool thing is that the namespace is automatically added to the class-name for your autoload function so you can do something like this
function on_load($class)
{ require_once('root/' . str_replace('\\', '/' $class)); }
If you want to learn more try googeling PHP auto-loading there is tons of information on this subject. But then again. From the format of you question I do not assume you're using OOP so this answer is just for the people who found this question on google.
Edit
I would also like to add the following:
// Only include the file once even if you place this statement multiple times
require_once('bla.php');
include_once('bla.php');
require('bla.php'); // Error if file doesn't exist, php will not continue
inlcude('bla.php'); // Warning if file doesn't exist, but php will continue
Using include or require without _once means that file will get included every time the statement is executed
Use include for template or user generated files, use require_once for classes

Just think easy, and think about load as less as possible and don't include something unnecessary.
So for your PHP files. if you include same php files on different pages just create 1 PHP file with this files in it.
If you use a PHP file in 1 page or 2 only, just include them seperate.
I hope i helped you with it ;)

Include files independently, use require_once() function instead of include, as require_once allow only one inclusion of file...

Related

how to include files based on order of inheritance

I have a list of files, wherein a file is inherting another file ion the same directory. I want to include all files of a directory, how do I do it in the order of inheritance so that I dont get any errors
Instead of calculating dependencies yourself, you might as well use auto loading using spl_autoload_register().
This way your dependencies get worked out as required. A bit like "Just-In-Time" loading :)
If your file/s have certain dependencies on other files, make sure you include the "parent" file/s first.
For example, you have a class A in a file A.php:
<?php
class A {
// .. statements
}
And you have a class B that extends A named B.php:
<?php
require_once( "A.php" );
class B extends A {
// .. statements
}
The idea is to "include"/"require" the needed files first prior to using any functions/classes/statement in that file. In PHP 5, you can use the auto-loading functions that would "automatically" add/include the file you need without the constant need of typing require functions.
You COULD use a parser to chek for dependecies but this would be a awfull lot of work and a real performance killer.
You could sort the files and prefix them with numbers
001.init.php
002.db_connect.php
003.pre_filters.php
But if you sort them manually it is rather pointles to rely on the file names.
If you have class inheritance you can combine a autoloader and require once.
Register an custom autoloader to require fles using require_once and and include all your files with a loop. If you need a class from the 8th file in your 4th file the autoloader will load the 8th file ahead of time and when your inlude loop reaches the 8th file nothing will happen because require_once will not include the file again.
But as you might already have realized:
Including files which are depending on each other in a random order from the file system is NOT a good idead.

php re-evaluate included files

I read about the class autoloading in PHP, but till now I didn't understand why we should use __autoload() method?
I read that
PHP doesn't use
this method becuase it has the handy little include functions,
include_once and require_once, that prevent you from loading the same
file more than once, but unlike a compiled language, PHP re-evaluates
these expressions over and over during the evaluation period each time
a file containing one or more of these expressions is loaded into the
runtime in this site why we should use autoloading,
but I don't understand what is the meaning of PHP re-evaluates in the above statement!!
why require-once don't solve the problem of loading php file more than once?
The original article is more clear when you read it more widely (see below) :
It simply says that __autoload() is smarter than include_once() because the function include_once() has to be coded explicitly when the class may be required, and also because this function needs to be processed each time it appears in order to know if the file given in argument is already loaded or not.
The other function __autoload(), on the contrary, can be called only once for several classes you may need. And then PHP tryes to load the corresponding source file only when a class definition is missing.
We can sum up this argumentation by saying: you need one include_once() for each Class/Function source, while only one __autoload() may be enough for a set of Class source having the same location rule.
Snippet of the article:
Why you should use an autoload function in PHP
The loading of classes is something that managed languages like Java
and C# don't need to worry about, class loaders are built into the
compiler.
[...]
PHP doesn't use this method becuase it has the handy little include functions, include_once and require_once, that prevent you
from loading the same file more than once, but unlike a compiled
language, PHP re-evaluates these expressions over and over during the
evaluation period each time a file containing one or more of these
expressions is loaded into the runtime. That is where the Standard PHP
Library (SPL), introduced in PHP 5, and the wonderful little _autoload
function come in to enhance the speed and uniformity of your PHP code.
__autoload is a magic function, that you define, that enables PHP to let you know when it doesn't have a class loaded, but that class
needs to be loaded.
The include_once statement itself is reevaluated whenever encountered.
for ($i = 0; $i < 100; $i++) {
include_once 'foo.php';
new Foo;
}
This will evaluate ("run") the include_once 100 times. That can be something of a slowdown. On the other hand:
for ($i = 0; $i < 100; $i++) {
new Foo;
}
When using autoloading, the logic for file inclusion will only be triggered once, the first time the class is needed.
but till now I didn't understand why we should use it
When you have structured and organized your work, because of the organization it results that you have many similar class files. The simpler example is an mvc, but not only, any custom structure will result in similar files containing a class, then because of the similarity you put them in the same folder and also you use a common file naming convention for example you can have a controller and a model directory.. check example file: employeeModel.php, statisticsModel.php, indexController.php, errorController.php
Well you can take advantage of this fact, check this customized autoload function:
/*** function to include model and view classes ***/
function __autoload($class_name)
{if(__DEBUG) eval(__DEBUG_EVAL);
/*** Load a model class ***/
$mfile=__SITE_PATH .'model/'.$class_name.'.php';//echo 'model file'.NL;v($file);
if (file_exists($mfile)){
include ($mfile);
if(__DEBUG) //store debug info before include
eval('error_log("autoload Success file exists: ".$mfile.NL);');
return true;
}
/*** Load a view class ***/
$cfile=__SITE_PATH .'view/'.'/'.substr($class_name,0,-4).'/'.$class_name.'.php';//v($file);
if (file_exists($cfile)){
include ($cfile);
if(__DEBUG) //store debug info before include
eval('error_log("autoload Success file exists: ".$cfile.NL);');
return true;
}
return false;
}
It also has a few lines for debugging that can easily be removed later. Because of similarity in things it can decide it self what to include and also to report errors when occur. Without this autoload function you would have to care that class files are availoable before use. Also this function will allow to include a file once, if you check carefully it does not use include_once, this means that autoload fires only when the file has not been seen before, in contrary to simple file inclusion which is fired every time the code is executed as very correctly decese notice it.
Conclusion Autload = fires once per file, automates things, so you execute a class directly without caring to include it.
Autoloading means if you need some classes to be included automatically in the scripts like
require_once ("class.user.php");
require_once ("class.module.php");
To avoid such code for each script you can use Autoloading functionality of php

Where to place include statements in a PHP class file

Where is it wisest to include files in a PHP class file? For example if one of the methods needs a external class, should I include the file where it is used in that method, or should it be done before the class? Or in the constructor? Or? What do you recommend? Pros? Cons? Or is it just a matter of taste really?
include_once 'bar.class.php';
class Foo
{
public static function DoIt()
{
new Bar();
}
}
vs
class Foo
{
public static function DoIt()
{
include_once 'bar.class.php';
new Bar();
}
}
I prefer it on top, the same convention as for #import/import/using in c/java/c# as it immediately lets you know what other classes your class is depending on.
You may also want to check out require_once() instead of include_once() as it will halt with an error instead of giving a warning when the included file contains an error. But of course that depends on what kind of file you're including and how critical you deem it to be.
I would say that it depends.
So, if there is a rather large code base, and you would prefer to keep the code loaded into memory each time there is a page request down to a minimum, then I would suggest only including the other php file when needed.
However, if that script is always needed, then include it at the top of the script.
It really comes down to the situation and requirements.
Hope that helps.
It depends on architecture you are using. Including files in the beginning is neat, but if that file prints text then you wont be able to manipulate headers etc.
When you are using MVC pattern controller should include class files.
If you're sure you need the file included, do it at the top. If you need files included on demand, you might want to look into spl_autoload_register() to ease the pain.
It is always good to include external files on top of the page. It will be very easy to locate later. If the included file is very large then include it wherever you need. See also the documentation for require_once and include_once.
There's also simply require and include. Know the difference between them and which to use when.

How does PHP see classes - only in include files?

In PHP are classes only seen when they are in an include file? In Java I can see them in another file without including that file in my current file. In PHP is the only way to see any given class to include it in your file? So I'm just including my class file(s) everywhere?
In PHP are classes only seen when they are in an include file?
Yes. However, in PHP 5, there is the new Autoloading feature that allows you to build a function that includes a file when a class name is invoked. That effectively makes it possible to auto-initialize classes.
The simple example in the manual (I extended it slightly) makes it clear how this works:
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1(); // Autoloader will load "MyClass1.php"
$obj2 = new MyClass2(); // Autoloader will load "MyClass2.php"
?>
Advanced autoloaders like Zend Framework's Zend_Loader_Autoloader (and the Standard PHP Library's spl_autoload_register(), cheers #ircmaxell) make it even possible to add different autoloading rules for different prefixes, allowing for libraries to be loaded from varying directories with varying naming conventions.
Generally speaking, yes. However, do note that includes are cascaded--in the sense that: if you include file a.php which includes file b.php, you can now see file b.php in your current file.
Also, PHP 5 offers Autoloading Classes which I recommend you take a look at:
http://php.net/manual/en/language.oop5.autoload.php
Yes -- PHP doesn't have any visibility into code which wasn't included directly in the file using the code.
However, instead of including (or the preferred method -- requiring) .php files everywhere, many developers choose to use the PHP autoload ability (http://php.net/manual/en/language.oop5.autoload.php) to automatically load the required file when you use a particular class.
Yes, for a class in a file to be available, that file has to be included.
Including a file can be done in a number of ways, either using the following functions:
include(filename);
include_once(filename) - which only includes the file if it's not already loaded
require(filename) - equal to include, except that the script will halt if file is not available
requier_once(filename)
Files can also be autoloaded through the __autoload or spl_autoload_register functions. More info on autoloading classes on PHP.net.
Yes only in include statements will you have access to the functions in other php files. PHP is by standard a Procedural language. It works from the top order down, so if you wish to perform class like includes look at Object Oriented PHP or include the files at the top of the php page.

In PHP Dependency Injection, do I need to "require_once" the php file where the dependency is defined?

Taking Fabien Potencier's example:
class User
{
function __construct($storage)
{
$this->storage = $storage;
}
// ...
}
Assuming the Storage class is defined in a different php file (say, storage.php), do I need to include it in this file where the injection is done via a require_once?
Thanks,
JDelage
You should be putting all your requires and includes at the head of the file - that certainly a style thing, but for one thing it allows you to see by glancing at the source, what other files are need by your PHP file.
There are two cases:
You will only ever use user.php and storage.php from other files (app.php say)
There are cases where you will use user.php and don't want to worry about remembering to require storage.php.
For #1 - you don't need to worry about requires, however there's no significant disadvantage to using require_once at the head of your PHP even if most of the time it'll have already been required.
For #2 - you need to use require_once at the header since you cannot use user.php without storage.php and the final page only knows it needs user.php.
short answer: Use require_once to include all dependencies for the code (to allow it to easily be used by other code)
note: You should only include direct-dependencies for the code. That is: if you have group.php that uses user.php, it should require_once 'user.php', but need not worry about storage.php since it isn't directly used, and user.php implicitly includes it (that being said - no significant performance disadvantage of being thorough if you wish)

Categories