Wednesday, August 31, 2011

Zend Framework Session usage and examples

Session handling was one of the boring topic in plan php atleast for me, but in Zend Framework it really shines. If you like to work with Object oriented programming, you will definitely become fan of it.
In this article I’m going to discuss some useful techniques of using Zend Framework Session and Session namespace.
Keep in mind that Both Zend_Session and Zend_Session_Namespace extends abstract class Zend_Session_Abstract. So both inherit methods avaliable in Zend_Session_Abstract automatically.
If you want to go under the hood, you can open Zend/Session/Abstract.php and have a look at the functions available.
Instead of delve into the function available, I’d rather discuss some useful techniques.
Although you can create Zend_Session class object, however I would recommend Zend_Session_Namespace object instead. You can instantiate session as
$sess = new Zend_Session_Namespace(’MyNamespace’);

Here the argument is optional, however it is better to pass it. If don’t pass, Zend Session Namespace will assign its name a string “default”.
To store values, you will need to do the following.
$sess->username = ‘you_name’;

Later in your code, you will need to do the following to retrieve value from the session.
    $session = new Zend_Session_Namespace(’MyNamespace’);

    $userName = $sess->username;

This was a simple example of how to assign values to session and later retrieve. Now I’m going to discuss some of its important method.
To check whether or not session exist, write the following.
    If (Zend_Session::sessionExist()) {

    // do something.

    }

sessionExist() is static method available in Zend_Session.

Another very important method is rememberMe() available in Zend_Session. This is used to make your session persistent.
Its syntax is
Zend_Session::rememberMe(60*60*24*7);

The number passed as an argument specify for how long the session will be available. What I have done means that session will be there for a week.
To destroy this you will need to call the following function on the logout of your application.
Zend_Session::forgetMe();

Another method
destroy(bool,bool), take two Boolean arguments. This destroy the entire persistent data. Keep in mind that Zend_Session_Namespace data will not be destroyed. You can retrieve that data even after you call
Zend_Session::destroy(false);

To completely logout you will need to do the following
Zend_Session::destroy(true);

We now passed true instead of false.
The above methods were anyhow related to Zend_Session class. To check the individual namespaces you can use the following function
Zend_Session::namespaceIsset(’MyNamespace’);

This will check whether the specified namespace has been set.
To unset the particular namespace, you will need to write the following.
Zend_Session:: namespaceUnset(’MyNamespace’);

Sending Email with attachment in Zend Framework

You may have used Php for sending emails in your application. I haven’t experienced it in plain php, so I don’t know whether its easy or difficult. I, however, know that Zend Framework provide very easy way for sending emails. You can even attach files with your email with single method call.
In this article I am going to discuss how to send email with attachments. Please do tell me whether it helped you or not.

In your controller, write something like this.
$emial_body = “<table><tr><td>Body of the email</td></tr></table”;

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($email_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();

This, although, will send email, however it’s not a good approach to create email in your controller as your mail body may contain thousands of words.

The best approach is to create a template, that contain the contents that will act as body of the email. To achieve this, create a file called emailExample.phtml in your /application/views/scripts/templates/ directory. And write the contents you want to put, those contents will serve as body of the email you are going to send.

I am having the following code in my emailExample.phtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <table>
    <tr>
        <td>
            all my contents here.
        </td>
    </tr>
    </table>
</body>
</html>



Now in your controller, write
$myView = new Zend_View();
$myView->addScriptPath(ROOT_DIR . '/application/views/scripts/templates/');
$html_body = $ myView ->render(emailExample.phtml');

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);

$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();

Here we are first creating an instance of Zend_View, call addScriptPath() to add script path- directory path where our template file reside and which serve as body of our email.
We then get the template by calling render() method on that view object, giving it the name of the template. The rest of the process is same, creating Zend_Mail object, setting body and so on.
Another question come to mind is how
to send an attachment?
This is pretty simple too.
First you will need to get the contents of the file, by calling a method file_get_contents(), like this.
$fileContents = file_get_contents(‘path/to/file’);

And then call a simple method called createAttachment (), as
$file = $mail->createAttachment($fileContents);

And set the name of the attachment as
$file->filename = "yourfile.doc";

Tuesday, August 30, 2011

Zend Framework Sql Join Exaples

You may have custom of using advanced queries. It often requires writing complex queries if you are working on enterprise, large scale web application(s).

The use of joins can never be ignored.

Zend Framework developers have done tremendous job by providing simple method for implementing joins.

Lets look some examples of different type of joins.

Before discussing joins lets consider we have two tables, “authors” and “books”.

These are associated with author_id.

1. Inner Join
The simplest query will be

$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinInner('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->order('column name ASC/DESC');

2. Left Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinLeft('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

3. Right Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinRight('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

4. Full Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC'); 

5. Cross Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

Once you write these queries, you can fetch a single row or multiple rows as

$result = $this->getAdapter()->fetchRow($select);
$result = $this->getAdapter()->fetchAll($select);

The first statement fetch only one row, while the second statement fetch the entire dataset.

Zend_Form and xhtml strict validation

When you use Zend_Form (or another Zend Framework component generating output) to display your forms, you want get valid xhtml code, depends on xhtml doctype. For instance, when using Strict tags need to be closed (/>).

To accomplish this, we need to set Doctype on View object (we can do this in Bootstrap)

$view->doctype('XHTML1_STRICT');

Now every xhtml code generated with Zend Framerwork component will be XHTML Strict valid.

Zend framework – disable layout

Sometimes we need to disable layout in some actions. We can achieve this inside controller action, by getting helper layout and disabling it.

$this->_helper->layout->disableLayout();

Zend_Db_Expr

new Zend_Db_Expr("NULL")
new Zend_Db_Expr("now()")

Use Zend_Db_Expr("now()") instead of php date("Y.m.d H:i:s")function.


Example:
        $data = array(
                    "created"=>new Zend_Db_Expr("now()"),
                    "enabled"=>0,
                    "deleted"=>0

                );
       
        $db->insert("table_name", $data);

Zend Framework Cheat Sheets


Zend Framework Dispatch Process Overview - zenddispatch_en.pdf

zend-framework-cheat-sheet.pdf

Zend Framework Tutorials on Youtube























Tuesday, August 23, 2011

How to Send Text Messages with PHP


Text messaging has become extremely widespread throughout the world — to the point where an increasing number of web applications have integrated SMS to notify users of events, sales or coupons directly through their mobile devices.
In the following tutorial, we will cover the fundamentals of sending text messages with PHP.

Below is a simplified diagram of how a message can be sent from a web application to a wireless device. 


We’ll break this down — one piece at a time:
  • The message is composed using a web application that is stored and executed on a HTTP server and then sent through the internet (“the cloud”) as an email message.
  • The email is received by a Short Message Service Gateway (SMS Gateway), which converts the message from an email message to a SMS message.
  • The SMS message is then handed to a Short Message Service Center (SMSC), which is a server that routes data to specific mobile devices.
  • The message is finally transmitted over the wireless network to the recipient.
Most wireless networks have a SMS gateway through which email messages can be sent as text messages to a mobile device. This is nice, because, from a developer’s standpoint, it is generally free—however, it is of course not a free service for the end user. Fees still apply to the recipient of the message and messages sent via email will be billed as a non-network text message.

Email to SMS

To send a SMS via email, you’ll generally require only two things:
  • The phone number or unique identifier of the mobile device you want to reach.
  • And the wireless network’s domain name (many can be found in this list of email to SMS addresses)
The following convention can be followed for most carriers: 

phoneNumber@domainName.com

phoneNumber is the phone number of the mobile device to send the message to, and domainName.com is the address for the network’s SMS Gateway.

To send a text to Mr. Example, you could simply add 3855550168@vtext.com to any email client, type a message and hit send. This will send a text message to phone number +1 (385) 555-0168 on the Verizon Wireless Network.


For example, I’ll send a text message to myself using Gmail.


When my phone receives the message, it should look like so:

PHP’s mail Function 

Let’s take things a step further. Using the SMS Gateway, we can send a text message via email using PHP’s mail function. The mail function has the following signature: 

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

You can read more about it here.
  • $to defines the receiver or receivers of the message. Valid examples include:
    • user@example.com
    • user1@example.com, user2@example.com
    • User <user@example.com>
    • User1 <user1@example.com>, User2 <user2@example.com>
  • $subject is rather self explanatory; it should be a string containing the desired subject. However, SMS do not require a subject.
  • $message is the message to be delivered. As mentioned in the PHP manual, “each line should be separated with a LF (\n). Lines should not be larger than 70 characters.”
To replicate the earlier functionality, we could write the following PHP code:

mail( '3855550168@vtext.com''''Testing' );

A Test Drive 

Let’s run a test with PHP to make that sure everything is setup correctly and that the mail function will, in fact, send a text message. Using the following code, we can run:  

var_dump( mail( '##########@vtext.com''''This was sent with PHP.' ) ); // bool(true)  

When my phone receives the message, it looks like so: 

As you can see in the image above, the message shows that it is from Gmail. This is because I route all my outgoing messages from my local server through that service. Unfortunately, as of this writing, I have been unsuccessful at altering the From header to reflect an alternate address. It seems that the email headers are stripped and replaced with headers prepared by the SMS gateway. If anyone knows of a workaround, please leave a comment and let the rest of us know!

Adding Usability

The Markup

With the basics out of the way, let’s take this idea and wrap a user interface around it. First we’ll set up a simple form:

<!DOCTYPE html>
 <head>
   <meta charset="utf-8" />
  </head>
  <body>
   <div id="container">
    <h1>Sending SMS with PHP</h1>
    <form action="" method="post">
     <ul>
      <li>
       <label for="phoneNumber">Phone Number</label>
       <input type="text" name="phoneNumber" id="phoneNumber" placeholder="3855550168" /></li>
      <li>
      <label for="carrier">Carrier</label>
       <input type="text" name="carrier" id="carrier" />
      </li>
      <li>
       <label for="smsMessage">Message</label>
       <textarea name="smsMessage" id="smsMessage" cols="45" rows="15"></textarea>
      </li>
     <li><input type="submit" name="sendMessage" id="sendMessage" value="Send Message" /></li>
    </ul>
   </form>
  </div>
 </body>

The Style

Next we’ll sprinkle in some CSS:

body {
 margin: 0;
 padding: 3em 0;
 color: #fff;
 background: #0080d2;
 font-family: Georgia, Times New Roman, serif;
}

#container {
 width: 600px;
 background: #fff;
 color: #555;
 border: 3px solid #ccc;
 -webkit-border-radius: 10px;
 -moz-border-radius: 10px;
 -ms-border-radius: 10px;
 border-radius: 10px;
 border-top: 3px solid #ddd;
 padding: 1em 2em;
 margin: 0 auto;
 -webkit-box-shadow: 3px 7px 5px #000;
 -moz-box-shadow: 3px 7px 5px #000;
 -ms-box-shadow: 3px 7px 5px #000;
 box-shadow: 3px 7px 5px #000;
}

ul {
 list-style: none;
 padding: 0;
}

ul > li {
 padding: 0.12em 1em
}

label {
 display: block;
 float: left;
 width: 130px;
}

input, textarea {
 font-family: Georgia, Serif;
}

This gives us the following simple form:


The Script

The most important part to this is the PHP script. We’ll write that bit of code now: 

<?php

if ( isset( $_REQUEST ) && !empty( $_REQUEST ) ) {
 if (
 isset( $_REQUEST['phoneNumber'], $_REQUEST['carrier'], $_REQUEST['smsMessage'] ) &&
  !empty( $_REQUEST['phoneNumber'] ) &&
  !empty( $_REQUEST['carrier'] )
 ) {
  $message = wordwrap( $_REQUEST['smsMessage'], 70 );
  $to = $_REQUEST['phoneNumber'] . '@' . $_REQUEST['carrier'];
  $result = @mail( $to, '', $message );
  print 'Message was sent to ' . $to;
 } else {
  print 'Not all information was submitted.';
 }
}

?>
<!DOCTYPE html>

  • The script first checks to see if the form has been submitted.
  • If yes, it checks to see if the phoneNumber, carrier and smsMessage variables were sent. This is useful in the case where there may be more than one form on the page.
  • If phoneNumber, carrier and smsMessage are available and phoneNumber and carrier are not empty, it is okay to attempt to send the message.
  • The message argument in the mail function should be 70 characters in length per line. We can chop the message into 70 character chunks using the wordwrap function.
  • phoneNumber and carrier are concatenated and then the message is sent using the mail function.
  • If data is missing or it cannot be validated, the script simply returns Not all information was submitted.
  • Finally, mail returns a boolean indicating whether it was successful or not. The value is stored in $result in case I needed to verify that the message was in fact sent.
Note: The mail method only notifies whether the message was sent or not. It does not provide a way to check to see if the message was successfully received by the recipient server or mailbox.

The Final Code

 <?php

if ( isset( $_REQUEST ) && !empty( $_REQUEST ) ) {
 if (
 isset( $_REQUEST['phoneNumber'], $_REQUEST['carrier'], $_REQUEST['smsMessage'] ) &&
  !empty( $_REQUEST['phoneNumber'] ) &&
  !empty( $_REQUEST['carrier'] )
 ) {
  $message = wordwrap( $_REQUEST['smsMessage'], 70 );
  $to = $_REQUEST['phoneNumber'] . '@' . $_REQUEST['carrier'];
  $result = @mail( $to, '', $message );
  print 'Message was sent to ' . $to;
 } else {
  print 'Not all information was submitted.';
 }
}
?>
<!DOCTYPE html>
 <head>
   <meta charset="utf-8" />
   <style>
    body {
     margin: 0;
     padding: 3em 0;
     color: #fff;
     background: #0080d2;
     font-family: Georgia, Times New Roman, serif;
    }

    #container {
     width: 600px;
     background: #fff;
     color: #555;
     border: 3px solid #ccc;
     -webkit-border-radius: 10px;
     -moz-border-radius: 10px;
     -ms-border-radius: 10px;
     border-radius: 10px;
     border-top: 3px solid #ddd;
     padding: 1em 2em;
     margin: 0 auto;
     -webkit-box-shadow: 3px 7px 5px #000;
     -moz-box-shadow: 3px 7px 5px #000;
     -ms-box-shadow: 3px 7px 5px #000;
     box-shadow: 3px 7px 5px #000;
    }

    ul {
     list-style: none;
     padding: 0;
    }

    ul > li {
     padding: 0.12em 1em
    }

    label {
     display: block;
     float: left;
     width: 130px;
    }

    input, textarea {
     font-family: Georgia, Serif;
    }
   </style>
  </head>
  <body>
   <div id="container">
    <h1>Sending SMS with PHP</h1>
    <form action="" method="post">
     <ul>
      <li>
       <label for="phoneNumber">Phone Number</label>
       <input type="text" name="phoneNumber" id="phoneNumber" placeholder="3855550168" /></li>
      <li>
      <label for="carrier">Carrier</label>
       <input type="text" name="carrier" id="carrier" />
      </li>
      <li>
       <label for="smsMessage">Message</label>
       <textarea name="smsMessage" id="smsMessage" cols="45" rows="15"></textarea>
      </li>
     <li><input type="submit" name="sendMessage" id="sendMessage" value="Send Message" /></li>
    </ul>
   </form>
  </div>
 </body>
</html>

http://net.tutsplus.com/tutorials/php/how-to-send-text-messages-with-php/

Monday, August 22, 2011

Useful php function: Crop String

    public function cropString($str, $len) {

        if ( mb_strlen($str) <= $len ) {
            return $str;
        }

        // find the longest possible match
        $pos = 0;
        foreach ( array('. ', '? ', '! ') as $punct ) {
            $npos = mb_strrpos($str, $punct);
            if ( $npos > $pos && $npos < $len ) {
                $pos = $npos;
            }
        }

        if ( !$pos ) {
            // substr $len-3, because the ellipsis adds 3 chars
            return mb_substr($str, 0, $len-3, 'UTF-8') . '...';
        }
        else {
            // $pos+1 to grab punctuation mark
            return mb_substr($str, 0, $pos+1, 'UTF-8');
        }
    }

Sunday, August 7, 2011

960 Grid System

As you might have heard, I recently launched a site for the templates that I created to use in my personal and professional projects. For lack of a better name, and because the numerals made for a nice logo, I’ve decided to simply refer to it as the 960 Grid System. It’s funny, because even though all I did was post a single tweet about it before going to bed Sunday night, viral word of mouth kicked in, and I’m already getting inquiring emails.
I should note that the 180 KB download size isn’t for the CSS framework alone. That download bundle is for all the files: printable sketch sheets, design templates for Fireworks, Photoshop, OmniGraffle and Vision + the CSS and HTML. The 960.css file itself is only 3.6 KB when compressed.
First of all, I made this for myself, to scratch an design itch. Not everyone will like it, and I’m okay with that. There’s an old saying: “You can please everyone some of the time, and some people all of the time.” I am not trying to accomplish either. I am simply sharing the grid dimensions that I have found myself gravitating towards over the past year or so. If others can benefit from that, then all the better. That being said, read on.

Browsers

I built the code in my grid system to accomodate all A-Grade browsers, as determined by Yahoo. At the time of this writing, that chart looks like…
 Note that IE5.x is nowhere to be found. That’s for good reason. There’s not enough market share for it to be important to Yahoo. Not only that, but even Microsoft has discontinued support for it. If you’re stuck in a position where you’re still having to code for that ancient browser, the best suggestion I have is to go peruse Authentic Jobs and find better employment.

Background

I first became interested in grid design via reading articles by Khoi Vinh and Mark Boulton. Initially, I must admit that I didn’t fully grasp the concept. But, the more I thought about it, the more I realized that this time-tested practice from printing works well on the web. Like it or not, web pages essentially revolve around boxy shapes. Inevitably, these rectangles have to come together in some way or another to form a design.
As long as we’re using shapes consisting of right angles, we might as well make some logical sense of it all. Some time after the intial work of Khoi and Mark, I happened upon an article by Cameron Moll, heralding a width of nine-hundred and sixty pixels as the optimal size for design. Basically, 1024×768 is the new 800×600, and 960 makes for a good magic number to utilize the wider canvas on which we paint.
After that seminal article, I have been basically designing on some subdivided variant of 960 pixels ever since. Last spring (2007), I found my groove, so to speak. It happened when I began to redesign my personal site. It’s still in the works, but here’s a sneak peek. As you can see, I’m eating my own dog food, as the future version of my site will use a 16 column grid.


I have yet to sit down and complete the redesign, since I am still finishing up my masters degree via correspondence, and because other paying freelance work came up, plus day job, etc. Chronologically though, I technically “began” work on my grid system before the release of Blueprint.
That’s not a value judgement, but helps to explain “why another grid framework,” because I had already started down that path by the time Blueprint was announced. I have used BP, on a project where I was required to use a documented code base, to ease future maintenance of the site. Though it was agreed upon, the designer on the project didn’t design according to BP’s dimensions. That was partially my fault, for not better communicating how it worked. By the end of the project, I had basically overridden nearly everything BP brought to the table.
That’s when I got to thinking, wouldn’t it be great if there was a way to streamline things, to get designers and developers thinking and communicating better? And, what if IAs were included in that workflow? That inevitably led up to what is now the 960 Grid System.

What it’s not

By far, the most common question I have received via email has been “How does this differ from Blueprint?” People seem to ask the question almost antagonistically, as if to say — “You’re wasting your time, because Blueprint already exists, and I like it better, so nanny boo-boo.”
For those people, I say, bravo. Please, continue to use whatever works best for you, and whatever you are most familiar and/or comfortable with. I am certainly not looking to draw up battle lines, or trying to change anyone’s mind about what framework to use, or even if one should be used.
One of the glaring omissions, or nice features, depending on how you look at it, is the way the 960 handles (or doesn’t) typography. There is a text.css file included, but this is mainly to ensure that there is at least a something in place, so that as you do rapid prototyping, common elements such as headings, paragraphs and lists have basic styling.
I haven’t gone out of my way to establish a vertical rhythm for text, as is described in the Baseline article on ALA. It’s not that I don’t see the value in it, I do. I think it’s an awesome idea, and a noble pursuit. However, it is fragile. All it takes is for a content editor to upload an arbitrarily sized, 173 pixel tall image, and all the subsequent elements are off-beat.
I see this as being more of a design choice, than something that needs to be standardized. In fact, most things that might be considered unique to a site design have been left out. I have specifically not set any text or page background colors. Call me lazy if you want, but that’s one thing I found myself consistently overriding when using BP. I’d wonder things like: “Why is there a <th> background color?”
I have also not put in pull or push image/quote styles, as those are things I rarely use, and I consider that to be a bit more design and contextually content oriented than related to page layout and prototyping. It’d be easy enough to write as a one-off in your own design stylesheet.
So, I hope you’ll forgive me if my grid system isn’t all you think it should be. Much as I like the The Beatles, I don’t exactly want to hold your hand.

Texting

After that underwhelming explanation of what the 960 Grid System doesn’t do, let me highlight what I consider to be the features. First off, some love for Linux users. The default font-family order is Helvetica Neue, Arial, Liberation Sans and FreeSans, with a generic fallback of sans-serif.
One thing I’ve found about Ubuntu is that the default sans-serif font is actually closer in width to Verdana than Helvetica or Arial. It’s not a big deal, but if you want text that looks relatively the same cross-browser, you need more than just a generic fallback for Linux users. This can be especially important if using the size of a particular font to approximate a certain width. It stinks to see carefully crafted navigation break to the next line.
In talking to my friend Yannick, he advised me that Liberation Sans is available by default on both Fedora and Red Hat distributions of Linux. It is also freely available under the GPL, so what’s not to like? If I had to describe it, I’d say the numerals are reminiscent of Verdana, but the rest of the characters map nicely to the dimensions (if not glyphs) of Helvetica.
From what I could tell via Jon Christopher’s article, FreeSans is the nicest looking equivalent to Helvetica available by default on Ubuntu. So, the text.css font-family list handles OSX, Windows, Linux builds.

Sizing + Spacing

Before we get into the pedantic debate about pixel font sizes, let me just say — Let’s not go there. I’m aware of all the arguments, and have even toyed with making elastic layouts. For me, it’s about ROI. You can spend countless hours toying with font-size inheritance, like I did on the Geniant Blog, or you can set sizes in pixels and get on with your life.
I’m aware that Blueprint’s text equates to 12px, but 13px is what YUI‘s fonts.css file specifies, and I actually quite like the way they’ve done their typography, aside from percentage based sizing being a bear to wrangle. We used it on the Geniant Blog, to great (albeit time-consuming) effect.
While I haven’t painstakingly set a vertical baseline, body text is 13px with a line-height of 1.5 (unit-less) = 19.5px. Most block-level elements have a bottom margin of 20px. So, that right there gets you pretty close to a consistent baseline. Just need to tweak line-heights on headings, etc.
The two block-level elements to which I did not apply bottom margin are blockquote and form. In strict doctypes, both of these require other block level elements to be inside of them. For instance, paragraph tag(s) inside a blockquote or fieldsets in a form. By not having any margins themselves, other blocky children can stack neatly inside.
I’ve also re-indented list items by 30 pixels on the left, so if you want hanging bullets, be sure to set that back to zero. I actually think hanging punctuation is pretty cool, but have yet to meet a client who agrees, so I erred on the side of caution in my CSS, in hopes of mitigating future arguments.

:Focus

I just wanted to briefly mention this, because it has to do with accessibility. While I personally think that Eric Meyer’s reset.css removal of :focus outlines is aesthetically pleasing, I think the right thing to do is to retain focus borders, for users that navigate links via a keyboard instead of a mouse.
This has been a longstanding gripe of mine with the Opera browser — the utter non-existence of any sort of :focus indicator. Anyway, you can remove the a:focus code in text.css if you want to have cleaner looking links, but know that you do so at the expense of accessibility.

Columns

One of the key differences between Blueprint and 960, aside from nomenclature, is the way the grid columns receive their gutters. In Blueprint, all the gutters are 10px wide (a bit too narrow for my taste), and are to the right side. The last column in each row needs class="last" to remove the margin. This means that neither the left nor right sides of a container have any spacing. For the most part, this is no big deal, but if a user’s browser is constrained, body text actually touches the browser chrome.
In the 960 Grid System, each column has 10px margin on both the left and right sides. This allows for the overall container to have a 10px buffer at the edges, and the margins combine between columns to form 20px gutters (a bit more room to breathe). Additionally, there is no need to add an extra class for the last column in a row.
In some unique cases, you might want grid units nested within a parent grid unit. In this case, you will need class="alpha" and class="omega" on the first/last child in each row. It’s a bit more work, but is more of a fringe situation, so it won’t come up as often.
I specifically chose grid_XX as the naming convention because for some reason, having a class named span-XX bothered my brain, since <span>, <td colspan="X"> and <colgroup span="X"> already exist in HTML. I guess I just like the idea of there not already being several tag/attributes with the same naming conventions. I also disliked the monotony of typing class="column ..." repeatedly, though to their credit, the BP guys have eliminated that necessity in their most recent build.
Much like with Blueprint, you can add empty columns before/after a grid unit, by specifying a class of prefix_XX and/or suffix_XX. The naming convention there was simply one of personal preference, as I admittedly tend to get confused by the word append, forgetting if it goes before or after.

Internet Explorer

Someone emailed me today asking about IE compatibility, and why there is no ie.css file included with 960. Simply put, it wasn’t needed to fix any of the grid aspects. IE6 has a wicked bug which doubles the margin on any floated elements. This could be a huge problem, but is easily fixed by adding display: inline to that which is floated. This causes no side-effects in any other browsers, so it simply lives in the main 960.css file.
You may find that IE6 and IE7 both get the spacing around <hr /> slightly off, by 7 pixels above and beneath, which is easily fixed by adjusting margins accordingly. To me, that’s an acceptable issue, and not really worth adding another CSS file with conditional logic in the markup. If you do end up creating a separate IE stylesheet, keep that in mind, and address it.

In the Clear

Lastly, I wanted to talk about the clearing methods included in the 960.css. First off is my personal preference, adding an innocuous bit of markup to clear all elements. I have already written about it extensively, so I won’t go over all that again. Basically, add class="clear" to a <span> or <div> that you want to disappear. The only effect it will have is to clear floats.
The other method is for all you markup purists out there, who don’t want to dirty your HTML. Instead, you can insert markup via your CSS. This technique is well documented already as well. Essentially, add class="clearfix" to elements to clear what’s contained inside them.

Licensing

The whole bundled package is free of charge, dual licensed under GPL and MIT. While I’m no suit, it is my understanding that these two licenses ensure that you can use the grid system in just about any situation. I must especially thank my friend Michael Montgomery for his informal advice, helping me to wrap my mind around all the legalese. He is a patent attorney by day, web ninja by night, and helped me wordsmith the 960 copy.

Official Site






Wednesday, August 3, 2011

Zend Framework: Last inserted id

$db->insert("table_name", array("field1"=>"value1", "filed2"=>"value2", "created"=>new Zend_Db_Expr("now()")));
                
$id = $db->lastInsertId();

Zend Framework: Difference between two dates

In response to a mailing list question, Thomas, the lead developer of the I18n components pointed out that to find the difference between two Zend_Dates, you just have to subtract them:

$date = Zend_Date::now(); 
$diff = $date->sub($birthdate); 
$diff->toString(); 

Useful tip, that I’ve put here mainly so that I can find it again when I need it!

Google Plus Style Animations with Jquery and CSS3

Google plus given an awesome kick to user experience, specially circles UI animations. I feel it’s great and new definition to have user experience design. I have tried circle rotation animation effect with Jquery and CSS3. Just few lines of code applying CSS styles using jQuery methods like .addClass() and .animation(). Take a look at these live demos with modern brewers.