简体   繁体   中英

Is it possible to route all URLs with dashes in FuelPHP?

In the following configuration is it possible to use a regular expression or any other method besides specifing each route to use controller thisisatest when URL is this-is-a-test/action ? Would I have to build/extend my own Router class?

<?php
return array(
    '_root_'  => 'home/index',  // The default route
    '_404_'   => 'error/404',    // The main 404 route

    //'hello(/:name)?' => array('welcome/hello', 'name' => 'hello')
);

/* end of config/routes.php */

The way I implemented this was to extend \\Fuel\\Core\\Router using the following. The router class works with a URI which has been passed through the methods in security.uri_filter from config.php so rather than modifying the router class methods I had my router extension add a callback to that array.

class Router extends \Fuel\Core\Router
{
    public static function _init()
    {   
        \Config::set('security.uri_filter', array_merge(
            \Config::get('security.uri_filter'),
            array('\Router::hyphens_to_underscores')
        ));
    }

    public static function hyphens_to_underscores($uri)
    {
        return str_replace('-', '_', $uri);
    }
}

You could just as easily add it straight to the configuration array in app/config/config.php by way of a closure or a call to a class method or a function.

The downside of this is that both /path_to_controller/action and /path-to-controller/action will work and possibly cause some duplicate content SEO problems unless you indicate this to the search spider. This is assuming both paths are referenced somewhere ie a sitemap or an <a href=""> etc.

I believe the router class does not have the functionality by default. You would indeed need to extend or create your own router class.

You can use the security.uri_filter config setting for that.

Create a function that converts hyphens to underscores, and you're done. You don't need to extend the router class for it. Just supply the function name (wether in a class or a function defined in the bootstrap) to the config, and you're off.

I know it's after the event, but this is for anyone else wanting this in future...

In order to avoid confusion between underscores and sub-folders I preferred to convert hyphens to camel-case, so routing URL this-is-a-test to class Controller_ThisIsATest .

I did this (in FuelPHP 1.4) by adding an anonymous function to the 'uri_filter' in the 'security' settings in fuel/app/config/config.php :

'security' => array(
    'uri_filter' => array('htmlentities',
        function($uri) { 
            return str_replace(' ', '', ucwords(str_replace('-', ' ', $uri))); 
        }),
),

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