Welcome Guest, Not a member yet? Register   Sign In
Routing tricks
#1

[eluser]meigwilym[/eluser]
Hi,

I've wanted to do this for a while, and figured it out today.

Say you have a controller to serve videos. I want the url structure to be http://example.com/videos (or http://example.com/videos/index) to show all videos, and http://example.com/videos/title-of-the-video to play the video.

This cannot usually be done, unless you name all your videos as class methods. I have two methods, videos->index() to show all videos, and videos->play() to play a video.

So I have a route defined thusly:

Code:
$route['videos/((?!index).*)'] = 'videos/play/$1';

This will send anything that does not match index to videos->play().

http://example.com/videos/ and http://example.com/videos/index will show all videos, and http://example.com/videos/title-of-video will show http://example.com/videos/play/title-of-video.

I've played around with it, and have not had any problems yet. I'm not a great regex expert so I wouldn't mind hearing from the more well informed if this is theonly and/or best way to acheive this.

Regards,

Mei
#2

[eluser]n0xie[/eluser]
Doesn't this work

Code:
$route['videos/(:any)'] = 'videos/play/$1';

You shouldn't have to add a rule for the index, since that's loaded by default when someone opens http://yourname.tld/videos
#3

[eluser]xwero[/eluser]
Why not
Code:
$route['video/.+'] = 'videos/play';
No difficult regex needed and it gives the title a better context, you don't write: let's watch Tron on videos.
#4

[eluser]meigwilym[/eluser]
I added the index filtering in case http://example.com/videos/index is loaded directly. I'm not 100% that this wouldn't come up so I try and add the belt and the braces.

Thanks for the replies!

Regards,

Mei
#5

[eluser]omar-303[/eluser]
It can be done without using routs....

you could use a _remap() function in the videos controller which check if the requested method exists in the class and execute it if not it deals with it as a video title
Code:
function _remap()
    {
        $requested_page=$this->uri->segment(2,'index');

        if(method_exists($this,$requested_page))//It's a real method
        {
            $this->$requested_page();
        }
        else
        {
            //Do whatever you want wit the video title stored in $requested_page
            //You can do something like that
            $this->video_title = $requested_page ;
            $this->show();
        }
    }
    function show()
    {
        $video_title = $this->uri->segment(3,$this->video_title);
        
        //Show the video
    }
    function index()
    {
        //List all videos
    }

By using this way you can show videos by this url : videos/show/video_title OR videos/video_title Wink
#6

[eluser]thePiet[/eluser]
Thanks meigwilym, you saved my day :cheese: !




Theme © iAndrew 2016 - Forum software by © MyBB