Home > Net >  Codeigniter 4: How can I access controller methods from a Controllers/api subfolder?
Codeigniter 4: How can I access controller methods from a Controllers/api subfolder?

Time:12-05

I'm creating a project with Codeigniter 4. Everything works fine, except for calls to controllers in an "Controllers/api" subfolder.

Server with Rocky Linux release 8.7 (Green Obsidian) ID_LIKE="rhel centos fedora". Apache Php 8.1

The url of the Usr.php controller is https://test.myweb.com/api/usr , that is, /home/test/public_html/app/Controllers/api/Usr.php

I try to see the content of any of the methods of Usr.php but it doesn't works. The answer is "404 - File Not Found. HTTP.controllerNotFound"

I have tried to put in app/Config/Routes.php:

$route['api/(:any)'] = 'api\$1';
$routes->resource('App\Controllers\api');
$route['api/usr'] = 'https://test.myweb.com/api/Usr';
$route['api/([^/] )'] = 'api/usr/$1';

$routes->get('api/usr', '\App\Controllers\api\Usr');

Without results. This is Usr.php:

<?php
namespace App\Controllers\Api;
use CodeIgniter\Controller;

class Usr extends Controller {

    public function index(){
        echo "OK INDEX";die;
    }
}

This is the .htaccess:

RewriteEngine On
#Deny Access
RewriteRule "^(.*/)?\.gitignore" - [F,L]
RewriteRule "^(.*/)?\_sql/" - [F,L]
RewriteRule "^(.*/)?doc-project/" - [F,L]
RewriteRule "^(.*/)?\.git/" - [F,L]
RewriteRule "^(.*/)?README.md" - [F,L]

#Force HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_ADDR} !=127.0.0.1
RewriteCond %{SERVER_ADDR} !=::1
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^(.*)$ index.php?/ [L]
RewriteCond $1 !^(index\.php|images|php|script|styles|js|css)

<IfModule mod_rewrite.c>
    RewriteBase /        
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

Any idea? Thanks.

CodePudding user response:

In CodeIgniter 4, we don't modify the file system/Config/Routes.php since it's part of the core CodeIgniter 4 framework. Any changes made there would likely be overridden after a framework upgrade. You should instead add your custom routes definitions in the file: app/Config/Routes.php.

CodeIgniter 4: Setting Routing Rules

Secondly, you seem to be mixing the CodeIgniter v3 with the CodeIgniter v4 route definition/rule syntax. I.e:

Upgrading from 3.x to 4.x / Upgrade Routing

test.myweb.com/api/usr/login

# CI v3 CI v4
route file path application/config/routes.php app/Config/Routes.php
route rule $route['api/usr/login']['GET'] = 'api/usr/login'; $routes->get('api/usr/login', '\App\Controllers\api\Usr::login');
controller path application/controllers/api/Usr.php app/Controllers/api/Usr.php

Addendum

In CodeIgniter 4, don't forget to disable auto-routing. I.e:

app/Config/Routes.php

// ...
$routes->setAutoRoute(false);
// ...
  • Related