Lazy with bitwise operators

There is a certain charm in using a single variable to store a bunch of boolean flags. Binary is convenient because it is all 1′s (true) and 0′s (false). The part I don’t like is assigning variables to each position in the binary number. When mapping out the variable, there are a couple of ways you may think of defining your flags. It would be somewhat convenient if you could write the binary numbers out like:

$is_user = 1;
$is_admin = 10;
$is_superhero = 100;
$is_troll = 10000000000000000;

PHP does not offer this convenience. Some devs might suggest hex notation (0×1, 0×2, etc) or something that makes me sad like using bindec(). Then there is the tried-and-true method of defining your variable for each position in the binary string:

$is_user = 1;
$is_admin = 2;
$is_superhero = 4;
$is_troll = 65536;

I prefer a more lazy approach (and I think it is more readable, personally) to defining my boolean flags; use the shift left operator <<

The shift left operator is basically multiplying a number times 2. Since the binary positions are powers of 2, I can define my flags like so:

$is_user = 1;
$is_admin = (1 < < 1); //2
$is_superhero = (1 << 2); //4
$is_troll = (1 << 17); //65536

I like writing it this way for a number of reasons:

    • the second number tells me which position the flag is in (starting from 0)
    • It is easy for me to tell when I’m running out of flags (you only get 32 bits per number!).
    • bitwise operations are fast

    I understand that there are many more ways I could do this (like the pow() function and others); but that would be less fun, right?
    Checking against my permission variable is easy with the & bitwise operator:

    if ($permission & $is_admin) { /* do admin stuff */ }
Posted in Code | Leave a comment

Sessions without Cookies in CodeIgniter

Why No Cookies?

I wrote a web application that is primarily used by university students. Students use it primarily from their school’s computer labs, libraries, and in their classrooms. They rarely access the application from their own computer. The most surprising (and frustrating) thing about this scenario is that at least half of these universities have disabled cookies on any school-owned computer.

This becomes a challenge because the cookie is the primary means that PHP keeps track of the session ID.  I saw 2 alternatives:

  1. Put the session ID in the URL
  2. Use POST instead of GET

I went with Option 1.  It isn’t ideal (session hijacking, anyone?) but I figured it’s the best I could do given the circumstances.

Standard PHP

When you disable cookies for standard (non CodeIgniter) PHP sites, the PHP parser does a little bit of magic. For example if your page contains an anchor tag:

<a href="/path/to/page.php">Click Me!</a>

PHP (with session cookies turned off) will render this:

<a href="/path/to/page.php?PHPSESSID=THESESSIONIDHERE">Click Me!</a>

It’s nice that PHP does that – but by default, CodeIgniter doesn’t have GET parameters enabled!

CodeIgniter Routing

CodeIgniter has a nice feature called routing that allows me to break the normal URI pattern of

/controller/method/parameter

Since I have no idea how many parameters any particular method will need, I can’t necessarily put the session id at the end of the URL. I also have the capability of adding folders where my controllers are, so I can conceivably have a uri with folders like this:

/folder/controller/method/parameter

or this:

/folder/folder/controller/method/parameter

I decided that it was best to use routing to put the session id in segment 1 of the uri (typically reserved for the controller – but could be a folder as well). My final pattern is now:

/session id/controller/method/parameter

I change /application/config/routes.php to ignore segment 1 when CodeIgniter is looking for the right controller:

$route['(\w*)/(.*)'] = "$2";

In my controllers, I make sure I retrieve the session id from the routed uri:

session_name('PHPSESSID');
$sid = $this->uri->segment(1);
session_id($sid);
session_start();

That’s it! Sessions without cookies using CodeIgniter.

Posted in Code | Tagged , | 2 Comments

Using a CSS framework – don’t style the structure!

I’m a fan of using CSS frameworks. Two in particular have come in handy; Blueprint and the 960 Grid System. I like the CSS framework for a couple of major reasons:

  1. Greatly reduce cross-browser frustration with visual elements
  2. Make it really easy to create complex table-less layouts

One of the major features of both frameworks is the use of columns for layout. Class names generally refer to the number of columns any particular div spans across.  The challenge that I’ve noticed many developers face is overcoming their desire to style these structural elements.  Take this example (using blueprint):

<div class="container">
  <div class="span-12">
    <p>Left side text</p>
  </div>
  <div class="span-12 last">
    <p>Right side text</p>
  </div>
</div>

What if I want a border around the left side? At first glance, you might think it would be easy to add an ID to the first div and give it a border, right? That’s actually a bad idea. Why? Because the grid portion of the CSS framework is made for structure and layout – not for style. Adding a border actually widens the div; which would break the column layout!

My recommendation is to add an additional “styling” div inside the structural div for any block styling you want to do (background color, padding, borders, etc):

<div class="container">
  <div class="span-12">
    <div style="border:1px solid #000; padding:1em;">
      <p>Left side text</p>
    </div>
  </div>
  <div class="span-12 last">
    <p>Right side text</p>
  </div>
</div>

While it may feel like you’re approaching “tag soup”, you still have cleaner markup than a table-based layout.

Posted in Code | Leave a comment

A useful use of SQL “LIKE”

I needed to update a set of records in the database where a “code” column followed a specific format:

prefix_shortname_number

As it turned out, there were a bunch of entries that I did *not* want to update that followed a similar format:

prefix_shortname_letter

This would have been bad:

UPDATE TABLE_NAME SET column_name = 'value' WHERE code LIKE 'prefix_shortname[_]%'

As luck would have it, SQL Server (I didn’t check this on MySQL) allows a little bit of semi-regex in LIKE statements.  This update statement worked perfectly:

UPDATE TABLE_NAME SET column_name = 'value' WHERE code LIKE 'prefix_shortname_[0-9]%'

SQL Server will match a single character within the range provided between the brackets; which was all I needed :)

Posted in Code | Leave a comment

To-do Lists with Vimwiki

One of my challenges (as evidenced by my epic fail with Project52) has been to maintain a list of things to do and getting them done.  I’ve tried a number of online services such as remember the milk (RTM), Todoist, and Ta-da List. Each of those are free online services that specialize in creating manageable lists of things to do.  Personally, I still use RTM (though only for specific types of tasks) because:

  1. I can use SMS (through twitter direct messaging) to create tasks
  2. I get SMS reminders when tasks are coming up
  3. There’s a cool gmail gadget that I use a lot

Usually the “speific types of tasks” for RTM are those non-specific things that are important but don’t require me to be in front of my pc.  things like birthday gift ideas, remembering to call the cable company about my bill, and reminding myself to check out a cool website are all tasks that I want to do at a certain time; but aren’t tied to a specific project/client/job and therefore don’t need to be “in my face” all the time.

“What’s the problem?” you may ask,  “These services are more than sufficient to handle even the busiest of schedules and largest task lists!”

I certainly agree with the assertion that those existing tools are sufficient to handle my needs.  I would argue, however, that the imposed workflow of those tools are what keep me from fully utilizing them.  Imagine this scenario:  I’m working on some code (in GVIM, of course)and realize a change needs to be made in a different part of the site

  1. I open new tab in my browser
  2. go to my todo list website
  3. log in (if the site didn’t remember me)
  4. find the correct list (i keep my lists based on clients and projects)
  5. add the new item to the list
  6. resume work

Not sure if that represents how I would always use it; I suppose I could skip the “open new tab, go to website, log in, find list” steps by just doing that part first when I start working on a project.  Regardless of whether or not there are ways to make the use of online to-do lists more efficient, I knew that there had to be a way to manage lists of things without leaving the comfort of my favorite editor.

Enter vimwiki (http://code.google.com/p/vimwiki/)

In a nutshell, the above scenario changes a little:

  1. :tabnew
  2. \ww
  3. navigate to the list
  4. move to list of items i’m working on
  5. o
  6. type in new task
  7. :up
  8. :tabr
  9. resume work

While that looks less efficient (9 steps instead of 6) – remember that my hands never leave the keyboard; so there’s no hunting around with the mouse followed by the click-and-wait web experience. I could also save a few steps if I leave the current project’s buffer open in the tab so I only have to switch to it when I need to add an item.

Commands explained:

:tabnew

Creates a new "tab" with an empty buffer

\ww

Opens my default wiki page

Navigating between pages is easy with the ENTER and BACKSPACE keys

o

Insert a new line under the curser and switch to Insert mode

:up

Update (Save) the current buffer

:tabr

Switch to the first tab

This probably seems more difficult than it needs to be.  Why not just have a text file with a list of items that need to be done?  I could have one text file for each client/project and be done with it!  Here’s where the real power of vimwiki comes into play.  Since I’m using wiki syntax to enter the to do items (I also like to take notes into my wiki files and describe requirements,etc), the finished files are then exportable to just about any wiki; so the data becomes portable.

There’s also a feature that lets me publish the wiki content into HTML files that I can view in my browser (if I so desire).

Overall, it took about 5 minutes for me to install, configure, and start using vimwiki with positive results.   I’m able to jot down notes and to do items quickly and efficiently and save them in a portable format.

Posted in Code | Tagged | 2 Comments

Code folding with VIM – the manual way

Now that I’ve been using VIM (GVIM, to be exact) for the last few months exclusively as my code editor, I’m finally becoming comfortable with the some of the more common keyboard commands.  For example, I was editing an unordered list yesterday and wanted to fill it will a bunch of items.  Without thinking, I put my cursor onto the list item I wanted to copy and typed:

yy10p

What did that do?  Copied the current line and pasted it in 10 times.  How many keystrokes would YOU have had to use in your editor?  A lot more, I’m guessing ;)

Anyway, code folding is a must-have when I’m editing.  When the HTML code is particularly long, I like to fold stuff out of the way so I can focus on what I’m working on rather than see all the surrounding document.  Rather than rely on indentation or syntax, it’s faster for me to use the ‘manual’ folding method.  You can temporarily set this mode on the current buffer with the following command:

:set fdm=manual

Once that’s done, folds can be created manually by typing

zf

Let’s say I’m working on a large HTML file and I’m on line 500.  I want to fold everything above where I’m working.  There are several ways to do this, but here’s how I did it today.  Assumption: my cursor is already on line 500:

jvggzf

Ugh – looks ugly…but it is effective.  Here’s what it does:

  1. j = move the cursor up one line (to line 499)
  2. v = switch to visual block selection mode
  3. gg = move the cursor to the top of the document
  4. zf = create a fold

The end result?  Everything above line 500 is folded out of the way.  Very handy :)

Posted in Code | Tagged | 3 Comments

Doctrine ORM with CodeIgniter: Introduction

I’m currently developing a website for scheduling a volunteer group. (I’ll announce that in a separate entry). For this particular project, I chose the following:

I’m going to focus on the Doctrine integration for this entry. I got the idea to try Doctrine from Burak‘s blog “PHP and Stuff”. I started with this entry on using CodeIgniter with Doctrine.

The idea is this – If you’re already accessing objects in PHP to handle things like form validation, creating users, logging in, etc; why not use objects to represent your data as well? Doctrine provides a really nice framework to help do just that.

Typically, I would write my CodeIgniter Models to include a method for each operation I would need to perform on a particular type of data (Typical CRUD)

<?php
//methods in a user "model" in code igniter
function insert_user($data)
{
  //SQL code to insert a user
}
function update_user($data)
{
  //SQL code to update a user
}
function get_user($user_id)
{
  //SQL to get user info from the database
}
function delete_user($user_id)
{
  //SQL to delete a user
}

Doctrine does things a little differently. The “model” is really just a definition of the User database table and its relationships rather than an object containing the SQL itself. The Doctrine library provides all of the behind-the-scenes database interaction for you.

Let’s say I have a user is defined like so:

  • First Name
  • Last Name
  • Email Address
  • Favorite Color

In doctrine, I can simply define the User object

<?php
class User extends Doctrine_Record
{
  public function setTableDefinition()
  {
    $this->hasColumn('first_name','string',50);
    $this->hasColumn('last_name','string',50);
    $this->hasColumn('fav_color','string',50);
    $this->hasColumn('email','string',100,array('email' => TRUE, 'unique' => TRUE));
  }
}

that’s it! I don’t need to do anything else to peform all the CRUD operations on any users. To create a user:

<?php
$u = new User();
$u->first_name = 'Jon';
$u->last_name = 'Trelfa';
$u->email = 'user@example.com';
$u->fav_color = 'blue';
$u->save();

I don’t think I need to repeat much of what Burak and the Doctrine project have already documented – so I will end this introduction for now. Stay tuned as I document my discoveries :)

Posted in Code | Tagged , | 1 Comment

Using jQuery’s .data() feature

jQuery has a feature that allows you to assign arbitrary data to DOM elements by way of the data storage methods.  I ran into a scenario today where this feature came in very handy.  Here is how the process works:

  1. The user clicks a checkbox in a list
  2. The checkbox’s parent <li> element is hidden using the “highlight” effect
  3. A new <li> element is created in a different list to show the user’s selection

The problem is the use of the highlight effect.  It was possible that a user could click on the checkbox twice (quickly) – which would perform step #3 twice!  Thus I would end up with 2 identical elements in the “selected” list.

I’m certain there are probably a zillion different ways to handle this scenario – but this is the one I chose…

Using the .data() method on the elements, I ended up with this code:

$('#available_container').find('input:checkbox').data('enableclick',true).click(function()
{
  if ($(this).data('enableclick'))
  {
    $(this).data('enableclick',false);
    $(this).parents('li').hide('highlight');
    add_item(this); //adds the new item to the "selected" list
  }
});
//here is the function when items in the "selected" list are clicked
$('#available_container')
  .find('li:has(input:checkbox[value=' + id + '])').show('highlight')
  .find('input:checkbox').data('enableclick',true);

This seemed the simplest way to temporarily disable the “click” event while the <li> was hiding itself and it works pretty well.

Posted in Code | Tagged | Leave a comment

Project 52

For me, “deciding” to start/stop doing something as a resolution for the New Year is far different than actually following through.  The good news is that I’ve found a way to better motivate myself.  How do I do it?

I publish my commitment

For whatever reason, telling my Facebook friends and/or blog readers (I think there’s 2 if you include me and myself) what I’m actually committed to doing actually motivates me more than just deciding on my own.

So I’ve put my name on the Project52 website as my published commitment to write at least 1 new article per week for the whole year.

I’m not sure if this one counts but since I’m technically already behind (last week was the first week of 2010 after all), I may go ahead and put a tick mark for week 1 :)

Here’s to 2KX :)

Posted in Code | Leave a comment