Jump to content

Elegant way to initiate database & other classes in PHP page


Azsen

Recommended Posts

Hi,

 

At the moment I have a database class which handles all my db queries and returns results etc. I also have two other classes, general and filesystem. The general class has methods that are used by parts of the site and the filesystem one handles files. To initiate them I have to use the following code:

 

require_once($_SERVER['DOCUMENT_ROOT'] . '/mysite/_private/library/database.php');
$db = new database();	//Create database object

require_once($_SERVER['DOCUMENT_ROOT'] . '/mysite/_private/library/general.php');
$gen = new general();

require_once($_SERVER['DOCUMENT_ROOT'] . '/mysite/_private/library/filesystem.php');
$file = new filesystem();

 

Ok so is there a way to clean this up so I don't have to include all these lines on every page? It seems every time the user goes to a new page they have to open up a new database connection. Ideally it would be good if php scanned my class files on the site and loaded them automatically rather than having to use a long require_once statements on each page.

 

Secondly is there much point in putting the library files in the _private directory? I heard it was a bit more secure by default but that was a while ago.

 

Many thanks!

Link to comment
Share on other sites

function __autoload($class_name)
{
      require_once($_SERVER['DOCUMENT_ROOT'] . '/sportsite/library/' .$class_name. '.php');
}

$db = new database();	//Create database object
$gen = new general();
$file = new filesystem();

 

Ok so that code works. But do I have to manually copy/paste that code onto every page of my site now?

Link to comment
Share on other sites

We use a system where index.php uses the url to determine which php file to include and which function to execute as the entry point from that php file (the function name is derived from the file name).  index.php includes everything that is required.

 

It's more or less back to front - the libraries include the code, rather than the code including the libraries, which means there is no code duplicated on every single page.

Link to comment
Share on other sites

Not quite sure I understand sorry btherl. Does autoload only have to be loaded once for the whole site, or once per page? If all the code to autoload the libraries is in the index.php then what happens if they first go to say admins.php? Example might help.

 

I was reading this on a website:

Usually, the __autoload function should be placed in a website wide configuration file which is included at the beginning of all PHP files of your website so it will only be written once. This way, all the classes of your website or application can be better named and prepared.

Where this website wide config file is and how do you tell it to execute?

 

Thanks :)

Link to comment
Share on other sites

The point of using a server side scripting language to make a site is you only need one file/page, so you are not even in a position to need to "copy/paste that code onto every page of my site now" because there is only one page that dynamically displays all the content and you only need to put the common code in once.

Link to comment
Share on other sites

Azsen, what I was talking about is basically what's in that bootstrapping article.  The details of our system are like this, let's say someone requests http://domain.com/admin.php.  Apache sends the request to index.php, which includes all the classes and libraries, meaning these are included only in one file.

 

index.php sees that the url is requesting the "admin" page, and looks for the script "admin.php" and the template "admin.html".  If it finds them, it includes admin.php and calls the function admin().  Any return values from admin() are passed to smarty for rendering the admin.html template.  If it doesn't find them then it will generate either a 404 error or redirect to another page, depending on the needs of that particular site.

 

Creating a new page is then just a matter of creating newpage.php and newpage.html, and the newpage() function.

Link to comment
Share on other sites

Ok thanks guys. It took a bit of work but I think I've got it working with the bootstrap by following that 2-part tutorial.

 

index.php

<?php
function __autoload($class_name)
{
	$path = "private/library/" .$class_name. ".php";

   		if(file_exists($path))
	{
        	      require_once $path;
    	        }
	else {
        	      echo "Class cannot be found: " .$class_name. ".php<br>";
    	        }
}

$db = new database();			// Initialise the database
$lib = new general();			// Make general class available

session_start();				// Start new session

$page = $lib->getPage();		// Get the page to load
require_once($page);

 

getPage() function

// Method determines which page should be loaded from the requested PHP page in the URL	
public function getPage()
{
	// Get just the page name from the URL
	$url = explode("/", $_SERVER['REQUEST_URI']);
	$url = array_reverse($url);
	$page = $url[0];

	// If page name isn't in URL or the page is index.php (bootstrap) then set to default homepage
	if (strpos($page, ".php") === false)
	{
		$page = "home.php";
	}

	// If page has GET variables set in URL, remove them so we just get the page name
	if (count($_GET) > 0)
	{
		$page = strtok($page, '?');
	}

	// If the page is index.php (bootstrap) set to default homepage
	if ($page == "index.php")
	{
		$page = "home.php";
	}

	return $page;
}

 

.htaccess file in site root

RewriteEngine on
RewriteBase /mysite/
RewriteRule !\.(js|ico|txt|gif|jpg|jpeg|png|css)$ index.php
php_flag magic_quotes_gpc off
php_value include_path "./private/library:./private/site:./private/includes"

 

.htacess file in /mysite/private

deny from all

 

Basically any request for a file on the website gets redirected to the index.php file which then loads up the database and library methods. The custom getPage() function then finds out what page was requested in the URL e.g. /mysite/home.php and then returns the name of the file "home.php" and loads that file as if you had gone to home.php directly. I needed to put a bit of code in there to remove GET code in the URL e.g. home.php?var=1&msg=2. I tested it with a form and you can still access the $_GET variables now.

 

By putting all the files (except images, css and js) in the private directory the web server stops people accessing them directly.

 

Am I on the right track?  Can I just include/require the header and footer manually on each included page now? Or should I be using templates. Things like Smarty etc look too complicated for me and I like doing things manually.

 

Also strange thing is when I access the url of a page directly in the /private folder e.g.

/mysite/private/site/home.php

then I get an access denied error. But if I access it like this

/mysite/site/home.php

and pretend the private directory isn't there it can find it/load the page fine. What's happening there?

Link to comment
Share on other sites

Am I on the right track?  Can I just include/require the header and footer manually on each included page now? Or should I be using templates. Things like Smarty etc look too complicated for me and I like doing things manually.

 

Yep looks like you're on the right track.  As for templating, that's entirely up to you.  If you do decide to learn about smarty you won't regret it.  Having a clean separation of the HTML and the back end allows you to do a lot more.  If you go further and make sure your core functionality is all in the classes and that those classes never access HTTP specific stuff like $_GET directly, then you your code is ready to plug into an XML or SOAP api.  Which you may never want to do, but anyway.. I always end up having to do that, so that's why I try hard to keep the presentation code (Smarty and HTML) separate from the back end code, and the interface code (HTTP, $_GET, $_REQUEST, $_SESSION) separate from the back end also.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.