Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include PHP files in a compatible way for packaging with and without Phar?

Tags:

php

require

phar

Given a PHP application with the following structure:

/
    lib/
        mylib.php
    web/
        index.php // includes "mylib.php" with: require_once __DIR__ . "/../lib/mylib.php"

I am trying to cover the following cases at the same time with the same source base:

  1. No Phar: Being able to use the application as is, with the DocumentRoot pointing on web/ and redirecting all requests to index.php.
  2. Minimal Phar: Being able to produce a phar that contains only web/index.php and that would be saved as: web/application-minimal.phar.
  3. Full Phar: Being able to produce a phar that contains both the content of lib directory and web/index.php and that would be saved as: web/application-full.phar.

In the case of phar files, all requests would be redirected to the phar file itself.

Is it possible to achieve all those use cases while not having to change the *require_once*?

I tried different approaches (relative/absolute) to include lib/mylib.php from *web/index.php", as well as trying some tricks with Phar::mount(). None of my attempts succeeded.

like image 445
Patrick Allaert Avatar asked Nov 13 '22 10:11

Patrick Allaert


1 Answers

Simply rely on your include path.

Don't do:

require_once __DIR__ . "/../lib/mylib.php";

but:

require_once "mylib.php";

and set the include path at the beginning of your script:

set_include_path(__DIR__ . '/../lib/' . PATH_SEPARATOR . get_include_path());
like image 191
cweiske Avatar answered Nov 15 '22 08:11

cweiske