Search code examples
symfonysymfony4

Symfony 4 controllers in sub folders producing error


Just a quick question as to why I'm getting this

The autoloader expected class "App\Controller\Admin\AdminUnitController" to be defined in file "/home/glen/public_html/businessdirectory.glendev.local/vendor/composer/../../src/Controller/Admin/AdminUnitController.php". The file was found but the class was not in it, the class name or namespace probably has a typo in /home/glen/public_html/businessdirectory.glendev.local/config/services.yaml (which is loaded in resource "/home/glen/public_html/businessdirectory.glendev.local/config/services.yaml").

I have AdminUnitController.php with class name AdminUnitController. All was well until I decided I want the admin controllers in their own sub folder like this:

Controller\Admin\AdminUnitController.php

Solution

  • From the autoloader message, your issue is quite clear, your file is indeed where it should be but your class or namespace is wrong.

    I would guess you changed the file structure but did not adapt your namespace.

    Given the file src\Controller\Admin\AdminUnitController.php

    Your class should look like this (pay specific attention at the namespace):

    <?php
    
    namespace App\Controller\Admin;
    
    class AdminUnitController 
    {
        // some code here
    }
    

    That is actually not a Symfony behavior you are facing here, but one of composer, that serves Symfony with the autoloader and that uses PSR-4 class autoloading convention.

    For Reference

    1) see your composer.json that have those lines:

    {
      // some definitions here
      "autoload": {
        "psr-4": {
          "App\\": "src/"
        }
      },
      "autoload-dev": {
        "psr-4": {
          "App\\Tests\\": "tests/"
        }
      },
      // some more definitions here
    }
    

    2) see the PSR-4 naming convention: and especially the examples in their documentation: https://www.php-fig.org/psr/psr-4/#3-examples