jQuery Tips

Posted on: Oct 26, 2009 by wenbert

Got this from Reddit.

  1. Load the framework from Google Code
  2. Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes
  3. Use Cheat Sheets
  4. Compress Javascript files
  5. Use Firebug
  6. Use ID as Selector whenever possible
  7. Use Tags Before Classes
  8. Cache jQuery Objects
  9. Bind certain jQuery functions to $(window).load event
  10. Use Chaining to limit selectors, make the code more simple and elegant

The complete article can be found in Tripwire Magazine.

Using Vim like an IDE

Posted on: Oct 19, 2009 by wenbert

I have been looking for a good and lightweight text editor for some time already. I have tried Notepad++, SciTE and others but was not satisfied with any. Although I have been using Vi and Vim to edit files on my server I have never actually tried to use it as a “local” text editor. This is the first time I have taken a deeper look at Vim. So here goes…

You can download Vim here: http://www.vim.org/. After that download these plugins:

I am using Ubuntu, so I created a .vim folder inside my home directory. The directory structure is something like this:

/home/wenbert/.vim
/home/wenbert/.vim/plugin
/home/wenbert/.vim/doc

Follow the installation instructions for the plugins after you download and extract them.

Here my .vimrc file can be found here.

How I use my vim

  1. I open Vim
  2. I issue this command “:NERDTree bookmark_name” (note: you must have an existing NERDTree Bookmark — see NERDTree docs on how to do this)
  3. I use NERDTree to browse and open the files.
  4. To close a buffer, I just use CTRL+W. The CTRL+W is mapped to :Bclose which closes the buffer without closing the window.
  5. I use CTRL+Arrowkeys to switch between the Bufexplorer, NERDTree and the current file I am editting.

jQuery: Setting defaults for Checkboxes, Radio Buttons, Options in Selectboxes

Posted on: Oct 06, 2009 by wenbert

I thought I should post this here. I always tend to look back at my old code wondering how I did these things.

Handling radio buttons or checkboxes

<input type="radio" name="print_memo" value="Yes"/> Yes 
<input type="radio" name="print_memo" value="No" /> No
<script type="text/javascript" language="javascript">
$(document).ready( function () {
    $('INPUT[name=print_memo][value="<?=$this->request->print_memo?>"]').attr('checked', true)
    /**
    * $this->request->print_memo will output either 'Yes' or 'No'
    * Here, we used INPUT[name=XXX] to select the form element
    */
});

For select boxes

<select id="country_id" name="country">
    <option value="1">Philippines</option>
    <option value="2">Singapore</option>
    <option value="3">Norway</option>
</select>
$(document).ready( function () {
    $('#country_id option[value="<?=$this->request->country_id?>"]').attr('selected', 'selected');
    /**
    * $this->request->country_id will output 1,2 or 3
    * Here, we used #country_id to select the form element
    */
});

Wordpress: Get sub-pages / children of Page

Posted on: Aug 31, 2009 by wenbert

I have been busy lately making some extra money doing side-jobs with Wordpress. In Wordpress, you will be able to create a “sub-page” by selecting a “Parent”. This tip is useful when you want to retrieve all the sub-pages. You should be able to use this code anywhere in your template files.

<?php 
global $post;
$args = array(
    'title_li'     => 'More Under This Page',
    'child_of'     => $post->ID
);
$children =  get_pages($args);
if($children):
?>
<div class="subpages">
	<ul>
	 <?php
	 wp_list_pages($args);
	 ?> 
	</ul>
</div>
<?php
endif;
?>

If your page has sub-pages / children under it, then it should display this HTML:

<div class="subpages">
<ul>
    <li class="pagenav">
    More Under This Page
        <ul>
            <li class="page_item page-item-46">
            Subpage 1
            </li>
            <li class="page_item page-item-49">
            Subpage 2
            </li>
        </ul>
    </li>
</ul>
</div>

MySQL: Doing calculations on dates excluding weekends

Posted on: Aug 14, 2009 by wenbert

I recently had to calculate the amount of work done by an employee between a specific date range. My problem was that the calculation must exclude the weekends. I asked around (both Google and #mysql in IRC) and found out that MySQL has a DAYOFWEEK() function.

DAYOFWEEK() takes a date and then returns 1 for Sundays and 7 for Saturdays. So for example, if I feed it using the date tomorrow which is 2009-08-14, I get 7.

mysql> SELECT DAYOFWEEK(  '2009-08-15' );
+----------------------------+
| DAYOFWEEK(  '2009-08-15' ) |
+----------------------------+
|                          7 |
+----------------------------+
1 row in set (0.00 sec)

If I feed it August 30, 2009 — it would return “1″ because that day is a Sunday.

mysql> SELECT DAYOFWEEK(  '2009-08-30' );
+----------------------------+
| DAYOFWEEK(  '2009-08-30' ) |
+----------------------------+
|                          1 |
+----------------------------+
1 row in set (0.00 sec)

With these examples on mind, we can come up with queries such as these:

SELECT
sum(orders) AS total_orders
FROM orders_table
WHERE
(date_created BETWEEN '2009-08-01' AND '2009-08-15') AND
DAYOFWEEK(date_created) NOT IN (1,7);

The query would fetch the sum of orders from August 1 to August 15 without counting the orders created on the weekends (August 1,2,8,9 and 15 — all of which are weekends).

Unit Testing My Zend Framework Application

Posted on: Aug 07, 2009 by wenbert

Okay, I have been getting into Unit Testing the past few days. With the help of Jon Lebensold’s screencast, I was able to jump right in quickly.

Right now I am looking into creating Mock Objects for my tests. I found this and this from zomg’s blog. Searching around, this is probably the easiest article to get myself started with Mock Objects in PHPUnit.

Slides/Article to read and screencasts to watch.

Posted on: Jul 30, 2009 by wenbert

From Matthew Weier O’Phinney:
Zend Framework Workshop from DPC09: http://www.slideshare.net/weierophinney/zend-framework-workshop-dpc09
and
Play-Doh: Modelling Your Objects:
http://www.slideshare.net/weierophinney/playdoh-modelling-your-objects-1766001
or you can view this: http://mtadata.s3.amazonaws.com/webcasts/20090724-playdoh.wmv

A screencast from Zendcasts.com about Unit Testing
- http://www.zendcasts.com/unit-testing-with-the-zend-framework-with-zend_test-and-phpunit/2009/06/

and something from Pádraic Brady
http://blog.astrumfutura.com/archives/411-Writing-A-Simple-Twitter-Client-Using-the-PHP-Zend-Frameworks-OAuth-Library-Zend_Oauth.html

A Follow-up on the Zend Framework Quickstart Tutorial: The Model

Posted on: Jul 22, 2009 by wenbert

The model is probably the most difficult to concept to grasp in MVC (Read Surviving The Deep End). This post is very rough and un-editted and is based on my experience.

I have gone through the new Zend Framework Quickstart Tutorial just a few days ago, and I found it hard to adapt to the new “data mapper” implementation in found in the models. Further reading will tell you that a Data Mapper is responsible for mapping a domain object to the database.

Quoted from MartinFowler.com

Objects and relational databases have different mechanisms for structuring data. Many parts of an object, such as collections and inheritance, aren’t present in relational databases. When you build an object model with a lot of business logic it’s valuable to use these mechanisms to better organize the data and the behavior that goes with it. Doing so leads to variant schemas; that is, the object schema and the relational schema don’t match up.

You still need to transfer data between the two schemas, and this data transfer becomes a complexity in its own right. If the in-memory objects know about the relational database structure, changes in one tend to ripple to the other.

The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn’t know even that there’s a database present; they need no SQL interface code, and certainly no knowledge of the database schema. (The database schema is always ignorant of the objects that use it.) Since it’s a form of Mapper (473), Data Mapper itself is even unknown to the domain layer.

In my example, I will be using a Model named “Group”. The group will contain an Id, Name, and Description. The SQL for this table will look something like this:

CREATE TABLE  `test_databases`.`group` (
    `id` INT NOT NULL AUTO_INCREMENT ,
    `name` VARCHAR( 100 ) NOT NULL ,
    `description_text` VARCHAR( 255 ) NOT NULL ,
    PRIMARY KEY (  `id` )
)

The Group Model
My group model that is found in application/models/Group.php contains something like this:

class Default_Model_Group 
{
    protected $_id; //a field
    protected $_name; //a field
    protected $_description_text; //a field
    protected $_mapper; //the mapper
 
    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }
 
    //__set() and __get() are built-in in PHP
    //they are called Magic Methods
    //http://us2.php.net/manual/en/language.oop5.magic.php
    public function __set($name, $value)
    {
        //Section A
        //What we are trying to do here is remove the underscores and camelCase the $name
        //so that we can call the $name as a Method within our class
        $pieces = explode('_', $name);
        foreach($pieces AS $key => $row) {
            $pieces[$key] = ucfirst($row);
        }
 
        //Section B
        //so $method below would contain:
        //$method = 'setDescriptionText' when you $obj->description_text = 'My Desc...'
        //we will look into this more in the following paragraphs...
        $name = implode('',$pieces);
        $method = 'get' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid group property');
        }
 
        //Section C
        //The code below will call the ff:
        //$this->setDescriptionText($value);
        //because $method is equal to "setDescriptionText".
        //setDescriptionText was created in Section A of this code snippet
        $this->$method($value);
    }
 
    //__get has the same idea as __set
    public function __get($name)
    {
        //again, we strip the underscores and camelCase
        $pieces = explode('_', $name);
        foreach($pieces AS $key => $row) {
            $pieces[$key] = ucfirst($row);
        }
        $name = implode('',$pieces);
        $method = 'get' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid group property');
        }
        //then we call the method...
        //For example: $this->getDescriptionText()
        return $this->$method();
    }
 
    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }
 
    public function setName($text)
    {
        $this->_name = (string) $text;
        return $this;
    }
 
    public function getDescriptionText()
    {
        return $this->_description_text;
    }
 
    public function setDescriptionText($text)
    {
        $this->_description_text = (string) $text;
        return $this;
    }
 
    public function getName()
    {
        return $this->_name;
    }
 
    public function setId($id)
    {
        $this->_twitter_id = (int) $id;
        return $this;
    }
 
    public function getId()
    {
        return $this->_id;
    }
 
    {
        $this->_mapper = $mapper;
        return $this;
    }
 
    public function getMapper()
    {
        if (null === $this->_mapper) {
            $this->setMapper(new Default_Model_GroupMapper());
        }
        return $this->_mapper;
    }
 
    public function save()
    {
        $this->getMapper()->save($this);
    }
 
    public function find($id)
    {
        $this->getMapper()->find($id, $this);
        return $this;
    }
 
    public function fetchAll()
    {
        return $this->getMapper()->fetchAll();
    }
 
    public function fetchGroup($id)
    {
        return $this->getMapper()->fetchGroup($id);
    }
}

Wow, I didn’t expect it to be that long. Anyway, here is our Mapper.

This is also found inside: application/models/GroupMapper.php

<?php
 
class Default_Model_GroupMapper
{
    protected $_dbTable;
 
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }
 
    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Default_Model_DbTable_Group');
        }
        return $this->_dbTable;
    }
 
    public function save(Default_Model_Group $obj)
    {
        $data = array(
            'name'   => $obj->getName(),
            'description_text' => $obj->getDescriptionText()
        );
 
        if (null === ($id = $obj->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }
 
    public function find($id, Default_Model_Group $obj)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $twitter->setId($row->id)
                  ->setName($row->name)
                  ->setDescriptionText($row->description_text);
    }
 
    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Default_Model_Group();
            $entry->setId($row->id)
                  ->setName($row->name)
                  ->setDescriptionText($row->description_text);
                  ->setMapper($this);
            $entries[] = $entry;
        }
        return $entries;
    }
 
    public function fetchGroup($id)
    {
        $quoted = $this->getDbTable()->getAdapter()->quote($id,'INTEGER');
        $resultSet = $this->getDbTable()->fetchAll('id = '.$quoted);
        return $resultSet;
    }
}

And finally, our Default_Model_DbTable_Group that is found in: application/models/DbTable/Group.php has only the following lines…

<?php
 
class Twitter_Model_DbTable_Group extends Zend_Db_Table_Abstract 
{
    protected $_name = 'group';
}

In my controller, I would just do something like this:

<?php
 
class GroupController extends Zend_Controller_Action
{
    protected $_flashMessenger = null;
 
    public function init()
    {
        /* Initialize action controller here */
        $this->_flash_messenger = $this->_helper->FlashMessenger;
    }
 
    public function indexAction()
    {
        // action body
    }
 
    public function saveAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->disableLayout();
 
        $group_name = $this->getRequest()->getPost('group_name');
        $group_desc = $this->getRequest()->getPost('group_desc');
 
        $group_model = new Default_Model_Group();
        $group_model->name= $group_name; //this is what I have been trying to tell from Section A above
        $group_model->description_text= $group_desc; //and this too!!!
        $group_model->save();
 
        $this->_flash_messenger->addMessage('You have added group: <b>'.$group_name.'</b>');
        $this->_redirect('/group'); 
    }
}

My email addresses and social networking accounts have been compromised. And Yahoo has a big security hole.

Posted on: Jul 18, 2009 by wenbert

My email accounts in Yahoo and Gmail have been compromised. My twitter account was deleted. If you want to contact me, please use the email found in my Resume.

Yahoomail secret questions are useless
I have changed my security/secret questions on Yahoo. But when I tested it, I noticed that there was a “This is not my question” link. When I clicked on the link my old and compromised secret questions were displayed! BIG FAIL!

UPDATE:
My twitter account still exists. The username and email was changed to “wenbertdelrosa“. Please note that any updates from that account does not anymore come from me.

Zend Framework: Creating your own view helpers

Posted on: Jul 16, 2009 by wenbert

This short tutorial assumes that you are using Zend_Framework 1.8, the latest stable release as of this post. To learn more about View Helpers, the Zend Framework Manual as an entire page for it found here.

First, you need to create a helpers folder inside: applications/views. So the structure of your directories will look something like this:

application/
----configs/
----controllers/
----layouts/
----models/
----views/
--------/helpers (This is the directory where all your view helpers will be stored.)
--------/scripts

Inside the helpers directory, create a file named BaseUrl.php. The file should contain something like this:

<?php
class Zend_View_Helper_BaseUrl {
    public function baseUrl() {
        $fc = Zend_Controller_Front::getInstance();
        return $fc->getBaseUrl();
    }
}

Usage:
To use your view helper, just do something like this in you view/layout files.

<!-- Assuming that this is a Layout / View file -->
The base URL for this application is: <?php echo $this->baseUrl() ?>
<!-- More HTML code here -->

© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!