Same namespace with files in different folders

Viewed 1927

I'm trying to structure a project so that some code that is auto generated is in a sub folder generated/, but it has the same namespace as files in the parent directory.

For example I have this structure which is giving me the error PHP Fatal error: Uncaught Error: Class 'MyProject\Foo' not found.

Is it possible to have the same namespace for 2 different files in different folders like this?

--lib/
----Foo.php
----generated/
----generated/Bar.php

lib/Foo.php

<?php

namespace MyProject;

class Foo {
  ...
}

lib/generated/Bar.php

<?php

namespace MyProject;

class Bar {

  public function __construct() {
    $foo = new Foo();
  }
}

My autoload section looks like this:

"autoload": {
      "psr-4": {
          "MyProject\\" : "lib/"
      }
  },
3 Answers

It sounds like you are using Composer for autoloading. You can configure composer to search multiple directories for a given namespace.

Here is some sample configuration(assuming PSR-4 autoloading)

{
    "autoload": {
        "psr-4": { "MyProject\\": ["lib/", "lib/generated"] }
    }
}

If you can provide the autoload section of your Composer project, I can provide more specific details.

It can only only work if you include the Foo.php at the calling the function.

As you have mention you are auto-loading the whole namespace with composer. Namespaces are like a virtual directory structure. In your case every class has same namespace so its trying to look all file in same directory because of which in your case Foo.php is not getting loaded via composer.

So Its better to different namespace directory wise or include them with path.

You are trying to use namespace without using use keywork. Try to follow the below code that will help you. As you are trying to access other class you will have to access via namespace otherwise you will fail to do that. follow below code.

<?php

namespace MyProject;

class Foo {
  ...
}

<?php

namespace MyProject;
use MyProject\Foo;

class Bar {

  public function __construct() {
    $foo = new Foo();
  }
}

Hope that this will work now.

Related