Welcome Guest, Not a member yet? Register   Sign In
Custom shorter URL's
#1

[eluser]RyanStubbs[/eluser]
Hey.

I was wondering if it was possible to shorten the URLs in CodeIgniter or bypass the standard CI URL system for one class. I am working on a user system and for ease of access, the shorter the profile URL, the better. I have currently got /profile/view/USERNAME but I believe that it is too long and would like something like /profile/USERNAME but I understand that it must be in the format of CLASS/FUNCTION/VARIABLE.

Is there a way to make it, for one class only, CLASS/VARIABLE? Can it be done with htaccess where the URL is completely masked and /profile/USERNAME is really /profile/view/USERNAME but the user does not see the view part?

Thanks.

Ryan.
#2

[eluser]fesweb[/eluser]
Yes, you can remap your controller this way
Code:
// immediately after the __construct()
function _remap($method)
    {
        if (method_exists($this, $method))
        {
            $this->$method();
        }
        else
        {
            $this->handler();
        }
    }

    
    function handler()
    {
// do whatever you need to do
$this->my_model->get_by_shortcut($this->uri->segment(1));

// if no records found:
show_404();
     }
// you can have other functions here if you like
function details() {}
function save() {}
function whatever() {}
Good luck.
#3

[eluser]mattpointblank[/eluser]
I'm new to CI, but I've been doing a lot of this and I just use the Routes config item (look in your /application/config/ folder and open routes.php).

You can add lines like this:

Code:
$route['profile/(:any)'] => '/profile/view/$1';

This basically sets a variable for 'any' characters and then uses that variable ($1) in the real URL (pointing to your 'view' function). Simpler and easier to update/add to.
#4

[eluser]jedd[/eluser]
That approach breaks if you have any other methods in your profile class.

fesweb's approach looks neat, but I haven't used it (I assume my users either get URL's handed to them through email, through my site, and/or they can cope with the word 'view' tucked in there). Because you are likely to only want to make an exception for view, I'd probably change the else bit to just throw straight to the view method.

Do you want shorter URL's, or specifically less segments? You could have your functions named by single letters. Heck, do the same with your controllers .. and say bye to that silly notion of meaning.
#5

[eluser]mattpointblank[/eluser]
True. Where I've been using it, I've had to make sure to add routes for other methods into the routes.php file before declaring the (:any) wildcard.
#6

[eluser]RyanStubbs[/eluser]
Thanks everyone for your help.

I've discovered that the routes method is the most appropriate and works the best with minimal coding so thank you, mattpointblank. Smile

Ryan.




Theme © iAndrew 2016 - Forum software by © MyBB