views:

63

answers:

3

I'm using global constants, like this:

/project
    /application
        bootstrap.php
    /public
        index.php

index.php

  • defines PUBLIC_PATH and APPLICATION_PATH
  • calls APPLICATION_PATH . bootstrap.php

bootstrap.php

  • defines LIBRARY_PATH, MODULES_PATH, TEMP_PATH, CONFIG_PATH, ...
  • does real work

Also i want to ask if there is better way to do this?

+1  A: 

You mean your application is not public? Anyway, normally I just define a ROOT constant in my front controller (usually index.php) like this:

define('ROOT', str_replace('\\', '/', __DIR__));

Or on older versions of PHP where __DIR__ is not available:

define('ROOT', str_replace('\\', '/', dirname(__FILE__)));

Since the inner structure never changes I just do something like:

include(ROOT . '/application/libraries/Email.php');

Instead of:

define('LIBRARY_PATH', ROOT . '/application/libraries');
include(LIBRARY_PATH . '/Email.php');

Less pollution. =)

Alix Axel
In my case PUBLIC_PATH is the same as you described:str_replace('\\', '/', `__DIR__`)application dir is intended to be outside web root (security measure) so it needs additional constant: APPLICATION_PATH
Hemaulo
@Hemaulo: Not really... You can use `/..` with the your `ROOT` constant.
Alix Axel
A: 

I am going for absolute path when possible, using $_SERVER['DOCUMENT_ROOT']
When impossible, I use relative paths, much like as Alix does.

Col. Shrapnel
A: 

According to your directory tree:

This is the one I would use to LOAD PHP script, basically you can place it in index.php or in bootstrap.php

define("PROJECT_DISK_PATH", str_replace('\\', '/', dirname(dirname(__FILE__))) . '/');
/*
Server variables $_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_FILE_NAME'] are both USELESS to 
accomplish this task because they both return the currently executed script and not this included file path.
*/

Then in your PHP script you do:

include(PROJECT_DISK_PATH . 'path/to/your/script/somescript.php')

And these are the ones I would use to LOAD JS/CSS script IN PAGES:

define("PROJECT_DOCROOT_PATH", '/' . substr(PROJECT_DISK_PATH, strlen($_SERVER['DOCUMENT_ROOT'] . '/')));
define("PROJECT_HTTP_PATH", "http://" . $_SERVER['HTTP_HOST'] . JPL_DOCROOT_PATH);

So in your page you can do:

   <script type="text/javascript" src="<?php echo PROJECT_DOCROOT_PATH; ?>path/to/your/script/somescript.js"></script>
Marco Demajo