I'm modifying a website and I would like to add a config file for it so that when when moving the website to another server, I only need to change environment parameters like database information only once. But I don't know how to apply the config file for the whole site. I tried to use include_once() and make it global using keyword global but it only works in the current file. If I don't use define() to make these parameters as constant, are there any other way to achieve this? Thank you.
You can create a class Config and store your config parameters as Class Constants. Then include this class everywhere you need it, or use Autoload it.
class Config {
const databaseUsername = "user123";
const databasePassword = "pass456";
}
echo Config::databaseUsername;
echo Config::databasePassword;
But as in my experience, define() works perfectly well, unless you need to store more complicated data types (arrays for example).
To avoid include the config file everywhere, you could set auto_prepend_file in your PHP.ini, but I personally find this solution obscure, since it's not obvious for another developer working on your code that a PHP file is auto-included.
Related
I am familiar with built in php functions such as str_rev, str_replace, etc... Is there a way to enable our own custom functions to be automatically to a php document instead of being forced to use include or require?
In other words, I would like to make my own custom built-in like functions that can be called without having to include or require a file prior to function call. Can this be done?
Typically, I don't consider global functions a good idea, however, yes, you can create a file, anywhere on your server and included in the php.ini file like so:
auto_prepend_file = "/path/to/global_functions.php"
Your php.ini will most probably already have the auto_prepend_file property so you may need to locate it and avoid having duplicate properties.
I have a class where I want to use an API, and I've got the api keys in a separate file in another directory.
The api key file is literally as simple as this:
$id = 'xxxxxxx';
$key = 'xxxxxxx';
This doesn't work:
include '/path/to/file-with-api-keys.php';
class MyApiClass {
public function __construct($id, $token) {
$this->client = new Client($id, $token);
}
}
The code where I instantiate the class is in another php file I'm using to test, and it's extremely simple, just includes the class and then instantiates it:
include '/path/to/MyClass.php';
$result = new MyClass();
$result->myMethod();
echo $result;
The error I get is basically saying the 2 variables are null.
TWO QUESTIONS:
1) How can I access the value of the variables in my constructor? I've read elsewhere that using an include file directly in the method is bad practice, and also that using a global variable would be bad practice as well.
2) Somewhat related question, these files where I'm storing the api keys are in the same directory with my database connection details, but the directory is not outside the root. In this directory I have an .htaccess file with "Deny From All". Is this sufficient from a security standpoint, or should I do something else?
ok 3 questions...
3) Should I even bother keeping the api keys in separate files within this directory or just embed them into my class?
Hoping someone can give me best practices here. Thanks!
The constructor won't read the variables from file-with-api-keys.php automagically. You must specify them like this when instantiating the class: $result = new MyClass($id, $key);
The best practice is to store all your PHP scripts outside the webroot directory except index.php (aka front controller).
Yes, you should bother :) All configuration, API keys etc. should be stored in separate files, outside your classes code. You shouldn't mix these two things. If you're going to use some version control system like Git, then you're going to commit your classes code without any configuration details. The latter will be in your .gitignore file. If you ever work in a team of programmers, then every one of them is going to have his separate configuration files.
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...
I'm using methods from a PHP class all over my code and I don't want to do "require_once" in every file I'm using that class. Is there a way to include the class in a single file, and then access it from everywhere in the code?
Thanks!
here ya go
http://php.net/manual/en/language.oop5.autoload.php
You could potentially use the auto_prepend_file directive (http://php.net/manual/en/ini.core.php), which you should be able to set via .htaccess if you have no other method of doing so.
What I want to do is this:
When I write a class and the class instantiates another class, I want to import that class with an require_once. Just the way I do so in Objective-C. But instead of using plain require_once function and messing around with paths and string concatenation, I would prefer something like:
importClass('myclass');
but I'm afraid that it's impossible to write a function that will include code. If I would do that in the importClass() function, I would include the class code into the implementation block of the function, which of course is nonsense. So what options do I have here?
The cleanest way to do what you want looks to be to use the Autoloader
It's not impossible at all. You can write this function:
function importClass($class) {
require_once "$class.class.php";
}
The only caveat is that any global variables declared or used inside that file will now be local to importClass(). Class definitions however will be global.
I'm not sure what this really gives you however but you can certainly do it.
In my application I have a system base class which has a similar function. The import function takes a class name, looks in a couple of related directories and finds a matching name (I also did some stuff with extensions to libraries but you may not need that) and instantiates a class inside with the same name. Then it takes that new instance and sets it as an object in the system base class.
using autoload as other answers have suggested would probably work better in your situation but this is just another way to look at it.
You can accomplish something similar using a class autoloader. I would also make sure that your include_path is set properly and that you are using a directory structure that makes sense for your classes - it's generally a good practice to NOT depend on class autoloaders, and instead include classes based on their relative path to your include_path.
I'd highly recommend browsing through Zend Framework, particularly Zend_Loader, for a good (if not over-architected) implementation. Also notice that Zend Framework will work without an autoloader in place - each file calls require_once on its direct dependencies, using their nice, organized directory structure.