phpcodeignitercontrollernamespacescodeigniter-4

How to work with subdirectory controllers in CodeIgniter 4?


I need help with using sub directory controllers in CodeIgniter 4.

I just can't make it work for some reason.

This is the URL for example: www.example.com/admin/dashboard

In the controllers folder, I created a folder named Admin, and a file named Dashboard.php.

I used this code in Dashboard.php:

namespace App\Controllers;

class Dashboard extends BaseController
{
    public function index()
    {

    }
}

I tried changing the class name to AdminDashboard, Admin_Dashboard, pretty much every logical name but every time I get a 404 error, saying:

Controller or its method is not found: App\Controllers\Admin\Dashboard::index

I know the file itself gets loaded successfully, but I think I don't declare the classname correctly and it keeps throwing me those 404 errors.

The documentation of CI4 isn't providing any information about what the classname should be called unfortunately...


UPDATE #1

I managed to make it work by changing few things:

namespace App\Controllers\Admin;
use CodeIgniter\Controller;

class Dashboard extends Controller
{
    public function index()
    {

    }
}

But now it won't extend the BaseController which has some core functions that I built for my app.

Any ideas to how to make it extend BaseController?

I must admit that I don't have much knowledge about namespacing yet, so that might be the reason for my mistakes.


Solution

  • As I imagined, the problem was that I didn't learn about namespacing. I needed to point the use line at the BaseController location.

    namespace App\Controllers\Admin;
    use App\Controllers\BaseController;
    
    class Dashboard extends BaseController
    {
        public function index()
        {
    
        }
    }
    

    Now www.example.com/admin/dashboard/ goes directly to that index function, as intended.