2

I'm looking for a way adding namespaces to the autoload PSR-4-Section in the composer.json file of my Laravel project, from the command line interface.

{
  "autoload": {
    "psr-4": {
      "App\\": "app/",
      "Modules\\": "modules/",
      /* add more here */
    }
  }
}

I was hoping there is a command like composer require, but I've not found a working command for this opportunity.

Did anyone come up with a proper solution for this?

Even a script for bash, powershell, php, ... would be appreciated. Being able to run it from the command line is the main thing.

3
  • Why would you need a command for that? How often are you going to add new namespaces?
    – Marwelln
    Commented Aug 11, 2017 at 17:42
  • 1
    To automatically deploy a setup for a developers environment.
    – MrMAG
    Commented Aug 11, 2017 at 17:57
  • We will not write a script for you, but a simple and effective way would be using PHPs json_decode() to convert the composer.json contents to an array, add the namespace definition, and json_encode() to convert the adjusted array to json again. This script simply be made executable by using php script.php, in your command line.
    – Jan Willem
    Commented Aug 11, 2017 at 18:09

1 Answer 1

5

If someone needs this,
I came up with this approach, which is working for me.

public function handle($key, $namespace, $output = 'composer.json')
{
    $file = 'composer.json';
    $data = json_decode(file_get_contents($file), true);
    $data["autoload"]["psr-4"][] = array($key => $namespace);
    file_put_contents($output, json_encode($data, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT));
}
1
  • JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT is most important piece of this code Commented Oct 21, 2019 at 11:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.