Absolute paths to files in Slim app

As i am not a fan of relative paths i find it pretty much annoying to write $_SERVER[‘document_root’] . ‘…/data/something’ whenever i want to work with files placed in data directory.

I have document_root set on public/, so i always have to add ‘…/’ in all of my paths to move one directory up and then go to desired directory from there. One way is to modify $_SERVER[‘document_root’] in index.php so it points to real root directory, not public. Other way is to define global const named ROOT_PATH or something like that, though i find this wrong as well.

How do you handle this trivial problem, when you want to use absolute paths to your files?

I would store the path in the container and use __DIR__ to specify the path relative to where the container variable is set (e.g. src/settings.php).

There is an example in the Slim skeleton application:

<?php
return [
    'settings' => [
        // ...
        'renderer' => [
            'template_path' => __DIR__ . '/../templates/',
        ],
   ]
];

Here the renderer template_path is set to /../templates/ relative to /src/dependencies.php.

For the case in your question, it would be something like:

return [
    'settings' => [
        // ...
        'data_something_path' => __DIR__ . '/../data/something'
    ]
];
2 Likes

I’m not sure if there is a best way or more proper way.
In app init I do:

define('DS', DIRECTORY_SEPARATOR);
define('ROOT', realpath('..') . DS);
define('APP_PATH', ROOT . 'app' . DS);

Then in config use the desired path:

return [
    'settings' => [
        // ...
        'views_path' => APP_PATH . 'views',
    ]
];
1 Like