user1518061
user1518061

Reputation: 77

Managing links and directories

I have recently started a larger project than I'm used to, and I'm finding it hard to manage links (such as including files) with all the directories.

Is there a way I can define a basepath and then go from there.

So something like this:

require(BASEPATH.'/folder/file.php');

instead of:

require('../../folder/file.php');

So basically a way so that the links won't break if files are moved.

Upvotes: 0

Views: 74

Answers (2)

Yang
Yang

Reputation: 8711

So you're saying you've started a large project - then you DO IT right from very beginning i.e from the current point.

I'd suggest you to create const.php contained this:

<?php

$constants = array(

   'DS' => DIRECTORY_SEPARATOR, //shorthand
   'ROOT' => __DIR__,
   'LIBS' => ROOT . '/libs'
);

//and so on - add more


//Define each one now:
foreach ($constants as $const => $val ){
  define($const, $val);
}

Any file of your project:

<?php


require ('../const.php');


//now constants are available and you can access them:
require ROOT . 'some.php'; //etc etc
require ROOT . 'another.php';

Upvotes: 1

rjz
rjz

Reputation: 16510

You can always store or define a variable based on the value of __DIR__ in your index file/front controller:

// in index.php
define('BASE_DIR', __DIR__);

In other files, you will now be able to reference the base directory like so:

// in some_other.php
require(BASE_DIR . '/folder/file.php');

Upvotes: 1

Related Questions