I like to figure things out and get things done.

wowr

Things I’ve Learned Using Codeigniter – PHP

1) You don’t need an ORM

I had experimented with Datamapper, and it was great. But there was complex join statement I needed that DM didn’t support… so I had to just write out the SQL like normal.  I then realized it’s just as easy to use CI’s Active Record or regular query command and create your own methods.  Plus, it keeps things pretty speedy.

2) You DO need a base Model

I’ve only just recently started using Jamie Rumbelow’s MY_Model and it’s changed everything. Previously, when I wanting to get a single record from a table, I was writing $this->db->from('table')->where('id',$id)->limit(1)->get()->row(); for every single table. Now, that’s already included for every Model I make.

3) It’s helpful to look at the core code

For example, I was curious how the Active Record was implemented, so I opened up DB_active_rec.php. I know some people prefer to use “->get()” by adding in the table name and limit as parameters, and I wondering if there was difference in how it’s handled.  Interestingly, it runs the exact same “from()” method, just as if you had “->from()” in the query.

And while this is a micro-optimization, if you want to return a single result and you’re sure it’s the first result… use “->limit(1)”.  The “row()” method will work with multiple rows returned, so there’s logic built in to just return the first row.  Adding “->limit(1)” will help skip all that.

4) The url helper really needs to be auto-loaded by default

In my autoload file, I always load the database and sessions libraries and the url helper. I can’t remember a project where those didn’t get used.  I’ll occasionally autoload the form helper as well, but that’s a project-by-project call.

But the url helper… I honestly can’t see how anyone would ever NOT use that in every project.  ”site_url()” and “redirect()” just seem like no-brainers.

5) Object-Oriented programming and MVC

Prior to learning Codeigniter, I was experience in Drupal and WordPress, and a bit of Joomla, but working with them isn’t strict OO.  The custom stuff I programmed was really procedural or functional, based on the fact that I learned programming using PHP 4 and classic ASP/ vbscript.  While I read about and tried using Classes and methods, I just didn’t get it. With CI, I had the ‘flipped switch’ moment, where Objects and Classes made total sense.

Now, I’m onto learning as much as I can about OO in PHP 5.3, including namespaces and inheritance… which aren’t yet built into CI

qbert2

Simple Facebook / Codeigniter Authorization

On a Codeigniter project I’m working on, I wanted to have Twitter and Facebook logins available. Luckily, right around the time I was starting the project, Elliot Haughin released libraries for both Twitter and Facebook. The Twitter library worked almost instantly and is quite brilliant. However, the Facebook library was causing me some problem.

Looking through the Facebook Developer pages, it seemed like a fairly straight-forward process to get a User’s Facebook auth tokens… and with CI2 having querystring support now, I thought I could do everything in a simple Facebook controller.  Here’s what I got:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Name:  Simple Facebook Codeigniter Login
 *
 * Author: Terry Matula
 *         terrymatula@gmail.com
 *         @terrymatula

 * Created:  03.31.2011
 *
 * Description:  An easy way to use Facebook to login
 *
 * Requirements: PHP5 or above
 *
 */
class Facebook extends CI_Controller {

    public $appid;
    public $apisecret;

    public function __construct()
    {
        parent::__construct();
        // replace these with Application ID and Application Secret.
        $this->appid = '12345';
        $this->apisecret = '123abc123';
    }

    /**
     * if you have a Facebook login button on your site, link it here
     */
    public function index()
    {
        // set the page you want Facebook to send the user back to
        $callback = site_url('facebook/confirm');
        // create the FB auth url to redirect the user to. 'scope' is
        // a comma sep list of the permissions you want. then direct them to it
        $url = "https://graph.facebook.com/oauth/authorize?client_id={$this->appid}&redirect_uri={$callback}&scope=email,publish_stream";
        redirect($url);
    }

    /**
     * Get tokens from FB then exchanges them for the User login tokens
     */
    public function confirm()
    {
        // get the code from the querystring
        $redirect = site_url('facebook/confirm');
        $code = $this->input->get('code');
        if ($code)
        {
            // now to get the auth token. '__getpage' is just a CURL method
            $gettoken = "https://graph.facebook.com/oauth/access_token?client_id={$this->appid}&redirect_uri={$redirect}&client_secret={$this->apisecret}&code={$code}";
            $return = $this->__getpage($gettoken);
            // if CURL didn't return a valid 200 http code, die
            if (!$return)
                die('Error getting token');
            // put the token into the $access_token variable
            parse_str($return);
            // now you can save the token to a database, and use it to access the user's graph
            // for example, this will return all their basic info.  check the FB Dev docs for more.
            $infourl = "https://graph.facebook.com/me?access_token=$access_token";
            $return = $this->__getpage($infourl);
            if (!$return)
                die('Error getting info');
            $info = json_decode($return);
            print_r($info);
        }
    }

    /**
     * CURL method to interface with FB API
     * @param string $url
     * @return json
     */
    private function __getpage($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $return = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // check if it returns 200, or else return false
        if ($http_code === 200)
        {
            curl_close($ch);
            return $return;
        }
        else
        {
            // store the error. I may want to return this instead of FALSE later
            $error = curl_error($ch);
            curl_close($ch);
            return FALSE;
        }
    }

}


That’s about it. You could put it all in “index()”, but I wanted to separate it a little.

update: Looking at the bit.ly api, it’s actually very similar. i’ll eventually try to make it more generic.

thumb_02

Motivations To Code

A few months back, I had an idea for a recommendation site for politicians/political candidates. The thought is, a user browses through a list of candidates that they can vote for, then clicks on an icon to “endorse” them.  I also wanted a way to not recommend a candidate by having a “reject” button. Then I would allow the candidates to include a script on their site that listed all their endorsements, ideally replacing/adding to the Endorsements page that many political candidates have on their site.

Basically, it’s a Facebook “Like” button, but with an option to “Not Like”… and all the candidates would be in one place.

The problem is, it’s just me doing all the coding and design, and being new to Austin, I don’t know anyone else that might be interested in helping out.  Add to that, the hours I spend at my  job, and having an 18-month old baby, and  going through a seemingly never-ending move… and it’s difficult to find the time, or the motivation to work on the project.

When I do find time, there will be brief spans of productivity and clarity.  Then eventually, I’ll hit a wall and a particular programming problem will stump me.  Instead of pushing through it with OCD abandon, I’d rather just stop and play with the baby.  This has been a circular pattern that has gone on for the past 9 months or so.

Tonight, I watched The Social Network movie, and the scene about the creation of FaceSmash made me long for the days when I would have an idea and stay up all night working on it.  Like when I bought a copy of “Creating Cool HTML 4 Web Pages” and spend all day and night reading every word, and creating “cool” web pages.  In those days, had I known PHP (or at least PERL), I would’ve had my endorsement site done in a week.  Of course, I didn’t have a full-time  job, a wife, or a baby at the time.

Then, I read the latest Email from Jason Calacanis and I’m not sure whether to be defiant or justified.  He basically argues that entrepreneurship is for single, young people… at least if it’s your first foray into creating something.  In the past, he’s also argued (essentially) that if you’re not working 18 hours a day, you’re not working hard enough. But I think 37 Signals shows that that isn’t always the case.

And no, I  don’t think my little idea would qualify me as an entrepreneur, but I think it is something that would have some appeal. I had also considered rolling it into another idea I’ve been working: creating nice-looking, dynamic web sites for candidates in local elections. In fact, I’ve got TONS of ideas… ideas constantly running through my head. Many times, I’ll spend a week or two on them, get them to a functional place, and stop.  And up until a year or so ago, I would immediately register a domain name to go along with it.

For example, TheMoviePunch.com was going to be a video blog where I reviewed movies, but only having viewed their trailer. Or ReindeerBlog.com was going to be one of Santa’s reindeer anonymously posting about the dark-side of working at the North Pole… and more recently, I was thinking about registering ReindeerLeaks, and then “leaking” documents about Santa, the elves, etc. And why do I own MrShoop.com?

So anyway, I’m now looking for the motivation to get back to coding, or more specifically finishing some coding.  My biggest motivation right now is just about learning new technologies and keeping my skills sharp.  But that doesn’t require a finished product… just a continual process. My hope is that I can blog more, and get these ideas I have out in the wild. At least that way they’re  not just filling up my brain space.

cgc_tn

College Guidance Consultants

A scholarship listing service, used by schools nationwide.  Custom PHP/mySQL application used for login, admin, and displaying the scholarships.

bang_tn

Bay Area Network Group

Business networking group in the Houston/Galveston Bay Area.  I created the entire site using PHP/mySQL , including a custom business directory.