Search code examples
phpsymfonysymfony4

symfony4.3 adding custom folder with classes


In my default symfony4 structure I want to add lib folder, where I have additional classes. So something like this:

-bin
-config
-lib
  - Importer.php
  ...(other files with classes)
-public
-src
   - Controller
      - TestController.php
   - Entity
   - Form
  ...
...

But I cannot figure out how to later use my files (i.e.: Importer.php).

Let's say Importer.php has a single class Importer() inside. If I try to use it from TestController.php I get:

Attempted to load class "Importer" from namespace "lib". Did you forget a "use" statement for another namespace?

TestController.php has

use Importer;

specified on top (autodetected by PhpStorm). I also tried adding namespace in my Importer.php file, for example:

namespace lib;

and then in TestController:

use lib\Importer;

But it produces the same result.

Lastly after reading about services, I tried adding the file to config/services.yaml

lib\:
    resource: '../lib/Importer.php'

Which gives the same result...

What to do, how to live?


Solution

  • First of all read about php namespaces.

    Next read about the psr-4 standart.

    Select a prefix for your folder, let's say Lib. Make sure that all files in the lib folder has a properly namespace. E.g. Importer class must be stored in the lib\Importer.php and must have the namespace Lib;, Items\Item class must be stored in the lib\Items\Item.php and must have the namespace Lib\Items\Item; and so on.

    Your files are ready. Just need to inform Symfony about them.

    Symfony uses composer's autoloader, so check composer's autoload section. Than add new folder for autoloading in composer.json:

    "autoload": {
        "psr-4": {
            "App\\": "src/",
            "Lib\\": "lib/"
        }
    },
    

    It says that all classes in lib folder have their own separate files and Lib prefix in their namespace and other part of namespace is similar to directories structure.

    Next you need to clear autoloader's cache. Run in console:

    composer dump-autoload
    

    And finally you can use your class:

    use Lib\Importer;
    
    $importer = new Importer;
    

    Also you can add your files to autowire.