How to determine the root directory for a project using Composer

I have an application ("foo") built in PHP that uses composer to match it. One of the dependencies is another project ("bar") that we created.

When adding a bar, composer, to the foo app, the bar needs access to the foo app's MySQL database. The database credentials are stored in the config directory in the foo app.

My file structure for foo looks something like this:

app/ # files for the foo app config/ # config information to access MySQL vendor/ # composer-managed files, including our bar app composer.json # information to load bar into the vendor/ directory

When I am developing a bar application myself, I need to be able to place the config / directory at the root of my bar development application and the bar needs to be able to access it. If bar is part of another composer project (foo in this case), I need it to know to go to the foo root for the config / directory, rather than look in the root directory.

How can the bar determine the correct directory for config /? I think I need to find the root of the composer installation, but I don't know how to do this.

In case a real-world example helps ...

I am using this foo app for Amazon OpsWorks. OpsWorks places the opsworks.php file in the root of the deployed application. I need my submodules (in my example above) to see where the opsworks.php file can be accessed in the root of the composer project. I need to be aware of the fact that composer may not be configured to place the bar in / vendor / but may have a different file structure configuration.

In other words, I want to ask Composer where the root for the application is.

+3


source to share


2 answers


If you look at https://getcomposer.org/doc/01-basic-usage.md

The section for autoloading describes the behavior you are looking for to search.



$loader = require 'vendor/autoload.php';
$loader->add('Acme\\Test\\', __DIR__);

      

You can define root foo and root bar this way and only load the elements you want.

0


source


You can use a very custom composer \Composer\Factory::getComposerFile();

to get into your project root:

$projectRootPath = dirname(\Composer\Factory::getComposerFile());

And in your case, you can access your directory config/

:



$configPath = $projectRootPath . '/config'

Don't forget to add composer

to your dependencies for \Composer\Factory::class

which will be available:

$ composer require composer/composer

0


source







All Articles