Friday, March 27, 2015

How not to prove your php skills

I'm always interested learning about ways of doing things. So when I came across an article about routing in php I was curious.

And then I saw the code.

32 lines to get one route?

The getCurrentUri function does 'magical' things with the SCRIPT_NAME and REQUEST_URI server variables.
The first thing I thought of was why don't they use the parse_url function?

And then it got worse on line 14 and 15, two $routes variables?
The idea is to get a array of the url segements. Line 15 is enough.

Now we are getting to the meat, the actual router. It reminds me of the time I used an asteriks in sql queries and referred to the fields as numbers, because I'm too lazy to type their actual names.

Because I was so outraged by this abundance of code, I wrote my own.

On line 3 you see how I get the path from the server global. For some reason PATH_INFO isn't set anymore, but REDIRECT_URL has the same value.

And then I'm doing my magic. Looking for the /search/book segments, stripping them when found and echoing everything that comes after them.

From 32 lines to 3, that is amazing!

PS: I commented on the article first but that was two weeks ago. My voice must be heard!

No comments: