Welcome Guest, Not a member yet? Register   Sign In
Routing with variable company name in URI
#1

Hi there!
I am attempting to create a custom routing rule that allows my application to have an optional company name "prefix" in the application URI's.
For example:
www.example.com/mycompany1/analytics/report
Where analytics is the controller and report the action method. Within the routing rule, I need to extract the "mycompany1" part and have CodeIngiter process the request as being "www.example.com/analytics/report". Existing controller names should take precedence over this rule.
In CodeIgniter 3 I was able to force the route by using a Closure function which using a regex was matched and by returning the effective routing URL:
Code:
$route["([a-zA-Z0-9\-]+)\/?(.*)"] = function (
    $companyShortname,
    $requestURI = null
) {
    // Prevent this route to override existing controller names
    if (
    file_exists(APPPATH . "controllers/" . ucwords($companyShortname) . ".php")
  ) {
        return $companyShortname . "/" . $requestURI;
    }

    // Do some processing to validate the company shortname (e.g. database lookup)
    // ...

    // Finally, route original request as if companyshortname wasn't present in the URI
    return $requestURI;
};
However, in CodeIgniter 4 I am unable to achieve the same result. Any suggestions are more than welcome.
Thanks!
Reply
#2

(This post was last modified: 03-17-2022, 11:20 PM by kenjis.)

The CI4's way is probably like this:
PHP Code:
$routes->get('(:segment)/analytics/report''Analytics::report'); 
The router in CI4 is completely different from CI3's.

If you want to force do like CI3, you probably need to write your own Router.

I might be wrong.
I'm not sure, but it might be a bug.

Try this:
PHP Code:
$routes->get('(:segment)/(:segment)/(:segment)''\App\Controllers\\\\$2::$3'); 

But I still don't recommend dynamic controller.
It seems dangerous.
Reply
#3

Thanks for your feedback. Based on your comments I think I better find another way to address the business requirement. For example, to have a single Controller/Action to select the company and subsequently store this in a session variable.

Thanks again!
Reply
#4

The original team decided that dynamic controllers was a security risk and did not implement them.

> We've had this brought up before but I have to turn down that feature. I view that as too big of a security risk because that allows anyone to try to load up common controller/method combos during an attempted attack. Not a good feature.
https://github.com/codeigniter4/CodeIgni...-608198225
Reply




Theme © iAndrew 2016 - Forum software by © MyBB