A Tinyurl.com-Like Application

I need to implement as simple as possible redirection application in Yii that will work like tinyurl.com and many, many others available in the Internet. I was thinking, if someone could give me any ideas where to start or what to look for.

This application should work two ways:

  • if URL is in the form: appurl.com/code, the RedirectController should be called, which will handle redirection, and code should be checked aganist db and proper destination URL should be taken from there,
  • if URL is a normal YII URL, containing valid route, proper controller and action should be called with all key-pairs passed in URL.

If there aren’t any ready to use out-of-the-box extensions or solutions, I think I can handle while application myself. But the URL management is the biggest pain (as always) for me.

For particular, I’m thinking if this will be better to solve upon urlManager, crafting some magic rule (don’t know which) so it will call either RedirectController when required or any other in any other case.

Or, if this would be better to solve basing on CWebApplication::catchAllRequest to route everything to one controller and write most of application code in that controller. It would then check URL string manually and decide whether redirection should take place or some in-app management will be executed.

Thank you in advance for any tips here.

I would create a URL rule for the URL shortener and then include this new rule in config/main.php,

and all the rest configure as standard Yii routes:


'urlManager'=>array(

	'urlFormat'=>'path',

	'showScriptName'=>false,

	'rules'=>array(

        	// URL shortener routes

        	array(

   			'class'=>'ShortenerUrlRule',

        	),

        	// Default routes

        	'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

        	'<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',

	),

),

This way, Yii first checks if the route is a URL shortener,

and if it’s not, then Yii moves on to create route as specified in the configuration.

Great idea! Thanks (+1)!.

But, what would be class ShortenerUrlRule example code? Should it be a normal PHP/Yii code for analysing URL and doing something with it, or should it be some extra urlManager rule (regular expression) only extended into own class?

I think it could be normal Yii code, for example something like this:

  • analyze the URL with regular expression
  • if expression matches, then query DB for possible shortened URLs
  • if shortened URL found, then do what is needed to redirect the user

I assume, that if extra class detects that URL contains code then it will do redirection and following urlManager rules won’t be executed.

On the other hand, if class won’t do redirection, it exit itself with doing nothing and following rules will be executed, as supposed.

Again, thanks for the idea. Seems interesting.