简体   繁体   中英

How to create a controller in a sub-directory in codeigniter v4?

In codeigniter v3 sub-directory in a controller is working fine. But in codeigniter v4 this is not working.

Folder structure: Controllers/[sub-directory name]/Controller_name.php

Need this Url: htp://domain.com/[sub-directory name]/controller_name/

How can I solve this in Codeigniter v4?

If you want to use the BaseController you have to specify "which one", using USE or you can explicitly specify it each time you use an object.

So you could have ( as deste had answered ) but using BaseController

<?php namespace App\Controllers\Ajax;

    class Test extends \App\Controller\BaseController // Which BaseController
    {
        public function index()
        {
            return 'controller works!';
        }
    }

OR the nicer way using "use" is to specify exactly which BaseController you want to use once.

<?php namespace App\Controllers\Ajax;

use App\Controllers\BaseController; // Which BaseController are you referring to.

class Test extends BaseController
{
    public function index()
    {
        return 'controller works!';
    }
}

It's a matter of telling PHP Where your files are.

Not the clearest of explanations but think of it as you have to say "where something is".

I strongly recommend reading over the Codeigniter User Guide a few more times and messing around with it more to get the hang of how it all works. You might also like to read Primer: Namespaces & CodeIgniter 4 by Lonnie Ezell (one of CodeIgniter's developers).

Using "Namespaces" and "use" you can create HMVC structures or anything you like. They are powerful and once you get the basics, very simple.

I am not so familiar yet with CodeIgniter 4 and namespaces... But I suppose that it's a namespace issue.

I have tried to replicate your case. I created a directory./App/Controllers/ajax and inside this a Test.php file:

<?php namespace App\Controllers\Ajax;

class Test extends \CodeIgniter\Controller
{
    public function index()
    {
        return 'controller works!';
    }
}

https://myserver/ajax/test page work fine. I hope this can help you in some way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM