Archive

Archive for August, 2009

Top navigation bar

August 30th, 2009 Chuck No comments

I liked how my CSS-based navigation bar turned out, so I thought of integrating it into my website’s design. As of this writing, I only included a basic “sitemap” menu and a filler menu for recent blog posts.

I’ll probably think of other things to add there as time goes by.

On closer inspection, adding that menu has a nice side effect towards search engine optimization, because a clean, straightforward list of URLs can be found at the very top of the code, before the other presentational bits. Which means search engines can see my site map a lot easier.

A neat and clean CSS menu

August 28th, 2009 Chuck 5 comments

Earlier this week, our team of developers was temporarily reassigned to help with another team’s debugging tasks due to a pressing deadline. Our front-end team was busy and only some of us from the back-end team were free to help.

The framework was based on Magento. Since our teams were all CodeIgniter developers, we found it hard to adapt to that framework. We were shocked to find out that majority of the fixes were front-end related, requiring mostly CSS and JS to fix. This was because navigating through Magento’s files was a pain. In addition, most of my teammates and colleagues from the other teams avoided the CSS bits because they either had limited CSS knowledge or were simply not confident enough to manipulate that website’s huge CSS file. So I took that task.

The website we were working on had a 3-tier navigation menu on top, controlled by JavaScript. I spent the better part of the day on that navigation bar building the content for the other menu and tackling the JS browser incompatibility problems… I previously mentioned in another entry that I suck at JS, needless to say what I did was a quick and dirty hack that works but one I’m not proud of, haha.

Anyway, 2 days later (that’s today), I was thinking – I bet it’s possible to mimic that navigation bar using purely CSS and no JS. So I set out and tried my hand at it. I relied heavily on nested  declarations in order to keep the styles neat and the markup less cluttered. Here’s the stylesheet I came up with:

html, body {
     margin: 0px;
     padding: 0px;
}
#navigation {
     width: auto;
     border: 1px solid #888;
     background-color: #EEE;
     color: #444;
     list-style: none;
     height: 22px;
     margin: 0px;
     padding: 0px;
     font-family: "Trebuchet MS";
     margin-bottom: 30px;
}
#navigation>li {
     float: left;
     width: 100px;
     text-align: center;
     height: 100%;
     cursor: pointer;
}
#navigation li:hover, #navigation>li:hover>a {
     background-color: #000;
     color: #FFF;
}
#navigation li a, #navigation li ul {
     text-decoration: none;
     color: black;
}
#navigation li a:first-letter {
     color: blue;
     font-size: 100px;
}

#navigation li ul {
     border-bottom: 1px solid black;
     border-top: 1px solid black;
     width: 100%;
     background-color: white;
     height: auto;
     display: none;
     position: absolute;
     float: left;
     left: 0px;
     list-style: none;
     overflow: hidden;
     padding: 0px;
}
#navigation li ul li {
     float: left;
     margin: 0px;
     clear: right;
     width: 200px;
     padding-left: 1em;
     padding-right: 1em;
}
#navigation li:hover ul {
     display: block;
}
#navigation li ul li:hover {
     background-color: red;
}

As for the menu’s markup itself, it consists of a master <ul> with an id of “navigation”, with nested <ul>s contained inside of it.

Here’s what the markup looks like:

<ul id="navigation">
<li><a href="#">Dogs</a>
     <ul>
          <li>Dog 1</li>
          <li>Dog 2</li>
          <li>Dog 3</li>
     </ul>
</li>
<li>Cats
     <ul>
          <li>Cat 1</li>
          <li>Cat 2</li>
          <li>Cat 3</li>
          <li>Cat 4</li>
          <li>Cat 5</li>
     </ul>
</li>
<li>Pigs</li>
</ul>
<div>Place your content here</div>

The markup looks really neat and simple with none of those pesky class="" attributes to get in the way. Also you can add as much menu items as you please.

So far this CSS declaration only supports 2-tier menus. I could try working on 3-tier, or even maybe a dynamic-depth CSS menu, if I don’t feel lazy :p.

You could see it in action by viewing this page.

Alternately, if you’re not a fan of horizontal menus, you can easily convert it into a vertical menu by removing the float: left; property in the #navigation li ul li declaration. Getting rid of the white background should be easy.

Update: August 29, 2009

I wrote another CSS declaration for 3-tier menus in vertical format. You could see the sample by going here.

Sorting uneven 2-dimensional arrays

August 27th, 2009 Chuck 1 comment

I was working on a search function for the module I was assigned to. The contents stored in the database isn’t plaintext, but rather encoded in base64. There’s currently no native MySQL functions to handle base64 data so that means I can’t make inline text and regex comparisons.

I thought hard about it and came up with 2 solutions:

  1. Save the data in plaintext instead and use heavy data validation
  2. Retrieve all rows and store them in a PHP array and do my regex magic there

Option 1 was out of the question, because in every part of the module, we’ve made sure to protect against XSS (cross site scripting). Going with this option will always risk creating a security hole regardless of how carefully I validate the supplied data.

Option 2 would be more secure and would allow me to apply my regex skills to the fullest extent, but it would cost more memory overhead because I’d have to retrieve the rows, store them into memory while doing the pattern matching…

Until I thought of option 3 (well, more like option 2.1). What I’d do is to limit the fetched rows by imposing more conditions, say for example, retrieve the rows that the currently logged user is only allowed to see. Then perform my regex thingamabob on those filtered results.

I had another problem though, doing this means I have to work on some sort of system to weigh the relevance of the results. Since this relevance value is computed after the database retrieval, this means I’ll be adding it into an extra column in the result array. The result array I am supposed to work on is a multidimensional array. It would have a similar structure as this example:

$data = array(
     array(
          'name'=>'Chuck',
          'color'=>'Blue'
     ),
     array(
          'name'=>'Rupert',
          'color'=>'Black'
     ),
     array(
          'name'=>'Cerrillo',
          'color'=>'Red'
     ),
     array(
          'name'=>'Abarro',
          'color'=>'White'
     )
);

The above array is a 2-dimensional array.  This means that echo $data[0]['name']; will display “Chuck”.

Anyway, as I earlier mentioned, I am supposed to add a relevance value to each row (or what I’d like to call weight). In addition, I might add some custom fields to some rows. Here’s how that array would look like with the additional fields and arbitrary weight values. (take note of the custom field added in line #6)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$data = array(
     array(
          'weight'=>20,
          'name'=>'Chuck',
          'color'=>'Blue',
          'custom'=>'Boo!'
     ),
     array(
          'weight'=>10,
          'name'=>'Rupert',
          'color'=>'Black'
     ),
     array(
          'weight'=>40,
          'name'=>'Cerrillo',
          'color'=>'Red'
     ),
     array(
          'weight'=>30,
          'name'=>'Abarro',
          'color'=>'White'
     )
);

By my weight system, the “heavier” a row is, the more relevant it is to the search query. So I should sort it by weight in a descending order.

PHP has a native array function called array_multisort();, so I tried that one. It doesn’t work with my array because the array sizes are not the same. I gave up a while after looking for workarounds to get it to work with that function, so I decided to write my own sorting function for arrays like these.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* 2-Dimensional Array Sort by Chuck Cerrillo (August 26, 2009)
* Sorts a 2-dimensional array according to a given field/index.
* This is particularly useful for sorting post-processed MySQL data (i.e. where
* custom fields have been added AFTER the retrieval of table data, and you'd need
* to resort the results).
*
* For more information on how to use this array, please visit my blog entry at
* http:///blog.chuckcerrillo.com/2009/08/sorting-uneven-2-dimensional-arrays/
*/

function array_2dsort($array, $field, $sort = 'asc'){
     $temp = array();
     
     // First we grab the index names of the sub-array
     // by walking through the array
     if(is_array($array)){
          foreach($array AS $subarrayindex=>$subarray){
               if(is_array($subarray))
               foreach($subarray AS $index=>$key){
                    // Store the fieldnames into the $fieldnames array
                    $fieldnames[$index][] = $subarray[$index];
                   
                    // We then store the field names into a temporary array
                    ${$index}[$subarrayindex] = $key;
               }
          }
         
          // Sort the temporary array based according to the $sort
          // argument, and maintain index associations by using
          // asort() or arsort()
          if(strtolower($sort) == 'asc')
               asort($$field);
          else
               arsort($$field);
         
          // Now we recreate a new array with the desired order
          foreach($fieldnames AS $fieldname=>$fieldindex){
               foreach($fieldindex AS $rowindex=>$rowvalue){
                    foreach(${$field} AS $index=>$value){
                         $result[$index][$fieldname] = $array[$index][$fieldname];
                    }
               }
          }
     }
     return $result;
}

Now this one works perfectly according to my needs. This function takes in 3 parameters,

  • $array – the array to sort (required)
  • $field – the field or index to sort by (required)
  • $sort – the sorting order, either asc or desc, defaults to asc (optional)

Given the above array, I would call my function this way – $data = array_2dsort($data,'weight');. If you would do a print_r($data);, it would give you this: (note that I didn’t specify ‘desc’ as my sorting order)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Array
(
    [1] => Array
        (
            [weight] => 10
            [name] => Rupert
            [color] => Black
            [custom] =>
        )

    [0] => Array
        (
            [weight] => 20
            [name] => Chuck
            [color] => Blue
            [custom] => Boo!
        )

    [3] => Array
        (
            [weight] => 40
            [name] => Abarro
            [color] => White
            [custom] =>
        )

    [2] => Array
        (
            [weight] => 50
            [name] => Cerrillo
            [color] => Red
            [custom] =>
        )

)

This function automagically adds blank fields to rows that do not contain them.

Regex saves the day, again

August 26th, 2009 Chuck No comments

I was supposed to do a “search” feature and a “related items” feature for the module I was assigned to. This was were my regex skills came in handy yet again.

I made a very barebone prototype of it, which takes some input text for the search query against some stored content, in this case, a full-text article (although the final version should be against a database).

The prototype I made is still very rough around the edges. What it does is that it extracts all keywords from the search query using this expression:

$regex = '/\b([\p{L}|\p{Ll}|\p{Lu}|_]+?)\b/i';

That rule can be translated as follows:

take any combination of unicode characters and underscores that are enclosed in word boundaries

Having done that, I place all matched data into an array and call that my “keywords” array, to be used later.

The next thing I did was to chop the article down into smaller pieces, currently by sentence (I only used periods as a delimiter, I should probably include other punctuation marks I guess). Then I ran preg_match() through each piece to quickly check for matches for any of the keywords. These results are then compiled.

In each compiled piece, I assign a corresponding weight. This weight is my arbitrary way of picking the best match. My currently implementation sets weight to be equal to the number of characters in the piece that are matched with keywords. I still have to refine these rules later on.

When all pieces have their weight assigned, I sort them according to weight in descending order (highest to lowest weight). Then I display the results and highlight the matched characters.

Here’s the prototype I made: search tool.

I’m still thinking of the refinements I could make so I’ll just post them here as I go along.

Also, it’s good to know that MySQL supports regex in your SQL queries, this should save me a lot of time!

Finally!

August 25th, 2009 Chuck No comments

After trying many many times since sunday, I was finally able to make my personal website appear at the very top of the Google search when you try to search for “Chuck Cerrillo”.

Curse my very basic SEO knowledge, lol.

At least I tried and it eventually worked.

Picking a JavaScript framework

August 25th, 2009 Chuck 2 comments

I had my own little experiences wrestling with JavaScript early into my webdevelopment days, but I never really went beyond simple DOM manipulation. JavaScript has always been overwhelming for me especially because I’d have to write different versions of the code as well as workarounds to ensure compatibility with most browsers… and I didn’t like rewriting stuff when I had to consider yet another browser.

Now,  a few years later, here I am again trying to get my feet wet with JS but at least there are several frameworks readily available to guide me through it, and take care of my problems (a pity they can’t help with personal problems, heh). I’m trying to choose from among the popular JS frameworks – Prototype, Scriptaculous, jQuery and Mootools. Based on my limited research, many devs prefer Mootools over the others, so I am thinking of starting with that.

So let me just formally state this before I begin…

Mootools, I choose you!

TheDirtLab logo

August 24th, 2009 Chuck 1 comment

I thought I put enough effort and attention to the main website’s design so far, so I figured I start working on the actual testing area’s theme. So here’s my second revision of the “laboratory” theme’s logo:

That’s Dirt the Lab in a lab-coat, presumably working in a lab, but I still have to draw in the lab, lol!

It’s 1:38pm (12:38am CDT) so I really should get to bed now, lest I risk not waking up in time for today’s work shift.

Yet another minor update

August 23rd, 2009 Chuck 2 comments

I was rearranging some stuff earlier today, I didn’t like how my alternate design turned out (the one with semitransparent content blocks partially overlapping with the top portion of layout). So I reverted to the original layout I made. I still have to work on the content area’s layout though.

Aside from that, I added two circular icons representing the major areas of the website. The first one being the home page and the second being this blog’s home page.

Also like previously mentioned, I coded in a little widget that grabs the ten most recent blog entries and displays their title and excerpt on the home page.

I’m still thinking what else to place into the home page though.

Conversion to MVC

August 22nd, 2009 Chuck No comments

You might not have noticed, but I’ve retrofitted my website to follow the  MVC pattern. What this means is that from now on I’ll be able to do my PHP/MySQL stuff on it, while keeping the designing part independent. This way I can keep writing scripts and whatnot, and not affect the layout.

As with any other MVC style websites I make, I start off with the global headers and footers. For that, I made a modified version of the original front page’s design to allow cramming of more content on-screen. I have made a test page using that view. So whenever I create new controller files, my constant parts of the layout will be kept, while the content for the pages change.

If you’re an coder and a designer, you might’ve heard of MVC architectural pattern (Model-Controller-View). It’s basically the separation of the program logic from the input and the presentation, allowing independent development, testing and maintenance of each part. In other words, if I only want to update the look, I don’t need to touch the scripts that involve the input and processing of data.

Minor design update

August 22nd, 2009 Chuck No comments

I’ve decided to ditch the “The Daily Random” concept since I already used that one before and it feels so old, so I’m going with my “TheDirtLab” idea as the main theme of my website, since I’m all about doing various coding junk! *lol*

Give me time and I’ll spruce up the front page with more content, and not just static content.

My next plan is to place everything into a PHP framework so I can work a lot easier within it.

If you’re interested on the technical aspect of the design,  what I did was work with multiple “div” layers and set a picture as a background image on them. This allows me to overlay pictures on top of each other while allowing the background to be seamless and still be stretchable. This should work on any screen resolution.

I used JPEGs for the looped background images (the fence and the grass), while Dirt’s profile and the Title text are PNG images. The use of PNGs allow me to create an illusion of a coherent merging of all the pictures so I won’t have to make much modifications to the source images if I want to add more elements to the background… say for example I wanted to add a “dog house” into the background. What I’d do is to simply draw the dog house in photoshop, make the background transparent, save it as PNG and place it in its own DIV layer on the HTML code. It’s that simple!