Sergio Díaz.

Being bored is boring AKA Introducing PHP Routs

I am probably the most bored person I know. What I mean by this is, that I am almost never entertained. Most of the time, I’ll be doing something for some 5 minutes before my short attention span takes me elsewhere. This has stopped me from finishing a lot of personal projects in the past, losing a lot of cool things I built halfway through. 

Since, I almost never finish my projects, I’ve decided to start publishing them. Hopefully, just knowing that others are looking at my code my motivate me to continue developing something. I’ve finally started using my Github account to it’s fullest. I honestly doubt it’ll actually have a great effect on me but, any motivation I might get will prove useful. So, in conclusion, I’ll be releasing most of the stuff I do whenever I am bored on my Github account and I’ll be posting about it here, all in an attempt to keep me interested.

Introducing PHP Routs

Let’s move on to my actual project. Routs, is a small PHP library built to handle URLs. Some background: I was playing with Sinatra the other day and, just by reading the documentation I fell in love with how it managed URL routes (I later discovered I wasn’t the only since, there are a bunch of projects written in PHP following it’s example). So, I decided I wanted to do the same in PHP but, in a very simple way which, would allow me to easily implement it into any project by including a single file.

It turned out to be a lot easier than I expected. After deciding on the syntax I would like to use with plugin I made huge advances in just a couple of lines. This is what I have so far:

Let’s say I am building an simple one page site for some guy named Bob. Since it’s so simple, I want to have as much as I can in a single page. Routs allow me to do something like this:


require 'routs.php';

Rout::get('home', 'homeFunction');

function homeFunction($params) {
  templateManager::Render('home.tpl', $params);
}

In this example I am using Routs to handle all get requests to example.com/home using the homeFunction() function. The part about the template manager is whatever method you’re using, I’ll be creating my own soonish. Now, I added a form to my html page and I want it to be handled on the same page. My routs handler changes into this:


require 'routs.php';

Rout::get('home', 'homeFunction');

function homeFunction($params) {
  templateManager::Render('home.tpl', $params);
}

Rout::post('home', function($params){
  mail(
    'seich@martianwabbit.awesome', 
    'Some Subject', 
    emailHandler::Render('mailTemplate.tpl', $params)
  );
});

Which handles the the submitted form and so on. Basically, the possibilities are endless! :D So yeah, that’s it, have fun with it, fork it, tell me why it sucks, etc.

comments powered by Disqus