Search code examples
phproutesframeworksurl-routing

Disabling the default routing system with Ubiquity-framework


I'm setting up a small application with Ubiquity Framework in PHP, and I'm trying to disable the default routing system (controller/action/parameters).

The routing system is based on annotations (documented here).

I have a controller with a few routes, which works (don't forget to reset the router cache).

namespace controllers;

class FooController extends ControllerBase 
{
    /**
     * @get("foo")
     */
    public function index()
    {
        echo "I'm on /foo";
    }

    /**
     * @get("bar/{p}")
     */
    public function bar($p='default p')
    {
        echo "I'm on bar/".$p;
    }

}

the addresses /foo, /bar and /bar/xxx are accessible, but I would like to disable the default routing system that allows access to the action of an existing controller (without route).

I want to disable the following urls:

  • /FooController
  • /FooController/index
  • /FooController/bar
  • /FooController/bar/xxx

I didn't find my answer in the doc.

I know the framework is not known (I discovered it through phpbenchmarks website), but the routing system is pretty classic, and it's still php.

If you have any ideas....

Versions:

  • php 7.3
  • Ubiquity 2.2.0

Solution

  • I found a solution, indirectly in the doc.

    The priority attribute of a route allows you to assign the order in which it will be defined (and therefore requested).

    To disable the call of actions on existing controllers, it is therefore possible to define a generic route in the last position returning a 404 error.

    namespace controllers;
    
    use Ubiquity\utils\http\UResponse;
    
    class FooController extends ControllerBase 
    {
        ...
    
        /**
         * @route("{url}","priority"=>-1000)
         */
        public function route404($url)
        {
            UResponse::setResponseCode(404);
            echo "Page {$url} not found!";
        }
    }
    

    If we still want to activate some controllers (the Admin part for example), we must add the requirements attribute, which allows to specify a regex.

    namespace controllers;
    
    use Ubiquity\utils\http\UResponse;
    
    class FooController extends ControllerBase 
    {
        ...
    
        /**
         * @route("{url}","priority"=>-1000,"requirements"=>["url"=>"(?!(a|A)dmin).*?"])
         */
        public function route404($url)
        {
            UResponse::setResponseCode(404);
            echo "Page {$url} not found!";
        }
    }
    

    In this case, the only routes accessible are those defined with annotations + those corresponding to the actions of the Admin controller

    With routing problems, routing solution.