I've been creating a small number of libraries / classes from scratch in php. I come from a codeigniter background, and I'm trying to make some libraries with similar functionality. I keep running into issues regarding objects.
Is the best way to create a super object $this
somehow? My main issue is that I've created a view object and I run a function called load
which looks like so:
class View {
public function __construct() {
}
public function load($file = NULL, $data = array()) {
if($file) {
$file .= '.php';
if(file_exists($file)) {
// Extract variables BEFORE including the file
extract($data);
include $file;
return TRUE;
} else {
echo 'View not found';
return FALSE;
}
} else {
return FALSE;
}
}
}
Then in my php file, I have at the top include 'libraries.php';
which looks like:
include 'database.php';
include 'view.php';
include 'input.php';
include 'form.php';
$config = array(
'host' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'database'
);
$database = new Database($config);
$view = new V开发者_JAVA技巧iew();
$input = new Input();
$form = new Form();
From the file which I included the libraries, I am able to write something like $form->value('name');
without errors. However, if I do something like this:
$view->load('folder/index', array('var_name' => 'var_value'));
then from the folder/index.php
file I can access $var_name
just fine, but not $form->value('name');
. I get errors such as Call to a member function value() on a non-object in ...
My question is how can I organize my libraries and classes in a way that will be reusable. I don't want to use a front loader (an index.php
file that everything runs through first). This may be an issue with the way I wrote my classes, but I imagine it's a larger issue regarding where things are located etc.
Put your library/class files in a common directory. Something like:
www
|_includes
| |_classes
| | |_view.php
| |_config
| |_database.php
|_other_folder
|_index.php
You can then set a common include path in your .htaccess file to this "includes" directory:
php_value include_path .:/path/to/www/includes
Then the other_folder/index.php file just needs something like:
require_once('config/database.php');
require_once('classes/view.php');
精彩评论