A CSV File and SQL Dump for all the zip codes in Philippines

Posted on: Mar 14, 2010 by wenbert

I spent a few hours yesterday gathering all the zip codes for the Philippines. This is public data, so I am sharing it with everyone. If you use it, I’d appreciate it if you credit me (It is not required but it would be great if you can send some traffic to my site — I have been planning to get a Linode but I can’t afford one yet :P).

Here is a preview of the CSV file:

"id","country","major_area","zip_code","city"
"1","PH","Abra","2800","Bangued"
"2","PH","Abra","2801","Dolores"
"3","PH","Abra","2802","Lagangilang"
"4","PH","Abra","2803","Tayum"
"5","PH","Abra","2804","Peñarrubia"
"6","PH","Abra","2805","Bucay"
"7","PH","Abra","2806","Pidigan"
"8","PH","Abra","2807","Langiden"
"9","PH","Abra","2808","San Quintin"
"10","PH","Abra","2809","San Isidro"
"11","PH","Abra","2810","Manabo"
"12","PH","Abra","2811","Villaviciosa"
"13","PH","Abra","2812","Pilar"
"14","PH","Abra","2813","Luba"
...
...
...
"462","PH","Cebu","6000","Cebu City"
"463","PH","Cebu","6003","Compostela"
"464","PH","Cebu","6001","Consolacion"
"465","PH","Cebu","6017","Cordova"
"466","PH","Cebu","6013","Daanbantayan"
"467","PH","Cebu","6022","Dalaguete"
"468","PH","Cebu","6004","Danao City"
"469","PH","Cebu","6035","Dumanjug"
"470","PH","Cebu","6028","Ginatilan"
"471","PH","Cebu","6015","Lapu-Lapu City (Opon)"
"472","PH","Cebu","6002","Liloan"
"473","PH","Cebu","6016","Mactan Airport"

The MySQL Table is like this:

CREATE TABLE IF NOT EXISTS `zipcodes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country` char(2) NOT NULL,
  `major_area` varchar(300) NOT NULL,
  `zip_code` varchar(25) NOT NULL,
  `city` varchar(300) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `major_area` (`major_area`),
  KEY `zip_code` (`zip_code`),
  KEY `city` (`city`)
) ENGINE=MyISAM

Updated: March 13, 2010 (2,270 zip codes)

Download the files below:

Corrections, suggestions, etc. just leave a comment below.

Enjoy!

CSS: Creating a horizontal menu/navigation bar

Posted on: Mar 10, 2010 by wenbert

I always forget how to do this. Every time I forget, it takes me about 10minutes searching for the right one. So I am posting it here for my reference.

My HTML would look something like this:

<div id="navbar">
    <ul>
        <li class="first"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Projects</a></li>
        <li class="last"><a href="#">Contact</a></li>
    </ul>
</div>

And my CSS would look something like this:

#navbar {
    background-color: #d90000;
}
 
#navbar ul {
    margin: 0; 
    padding: 0;
    float: left;
}
 
#navbar ul li {
    display: inline;
    list-style-type: none;
    padding-right: 20px;
}
 
#navbar ul li a{
    float: left; 
    text-decoration: none;
    color: white;
    padding: 10.5px 11px;
}
 
#navbar ul li a:visited {
    color: white;
}
 
#navbar ul li a:hover, #navbar ul li .current{
    color: #fff;
    background-color:#bf0000;
}
 
#navbar .first  {
    /*You can put stuff here for the first item in the navbar*/
}
 
#navbar .last  {
    /*You can put stuff here for the last item in the navbar*/
}

Comments or suggestions please ;-)

Zend Framework: How to use nested transactions with Zend_Db and MySQL

Posted on: Mar 05, 2010 by wenbert

Steve Hollis first blog post about practical nested database transactions using Zend_Db. He writes really well and his blog is very readable. I love reading long text in Serif :D Thanks Steve!

His solution:

The Solution
Disclaimer: This solution is adapted from the extended Pdo_MySql adapter in Varien’s Magento e-commerce product. A similar approach is adopted by Bryce Lohr’s Nested Table Support for Zend_Db proposal. You should read Bill Karwin’s comments about that proposal and understand the limitations of this method before implementing it. That said, I still believe this is a useful and practical way of simulating nested transactions and I have used it a number of times.

A simple solution to the problem is to keep track of the “depth” of the transaction, that is, how many times the beginTransaction() method has been called. That way, we can hold off committing the changes to the database until we are certain that all the save operations have completed successfully.

Since transactions apply to the whole database connection, the most logical place to manage this process is in the DB adapter class. To do this, we extend our adapter class like so:

App_Zend_Db_Adapter_Mysqli extends Zend_Db_Adapter_Mysqli
{
    /**
     * Current Transaction Level
     *
     * @var int
     */
    protected $_transactionLevel = 0;
 
    /**
     * Begin new DB transaction for connection
     *
     * @return App_Zend_Db_Adapter_Mysqli
     */
    public function beginTransaction()
    {
        if ( $this->_transactionLevel === 0 ) {
            parent::beginTransaction();
        }
        $this->_transactionLevel++;
 
	return $this;
    }
 
    /**
     * Commit DB transaction
     *
     * @return App_Zend_Db_Adapter_Mysqli
     */
    public function commit()
    {
        if ( $this->_transactionLevel === 1 ) {
            parent::commit();
        }
        $this->_transactionLevel--;
 
        return $this;
    }
 
    /**
     * Rollback DB transaction
     *
     * @return App_Zend_Db_Adapter_Mysqli
     */
    public function rollback()
    {
        if ( $this->_transactionLevel === 1 ) {
            parent::rollback();
        }
        $this->_transactionLevel--;
 
        return $this;
    }
 
    /**
     * Get adapter transaction level state. Return 0 if all transactions are complete
     *
     * @return int
     */
    public function getTransactionLevel()
    {
        return $this->_transactionLevel;
    }
}

Update your bootstrap to use the extended class et voila – a single START TRANSACTION and COMMIT or ROLLBACK is sent to MySQL, regardless of how many levels of nested pseudo-transactions have been created.

Please Note:

  1. It’s important that each child save() method re-throws the exception so that transaction depth is reduced by successive calls to rollBack(). The end result is that the originally called save() method then performs the actual rollback.
  2. All the tables used in the transaction must use a storage engine that supports transactions. For MySQL, this will most likely mean using InnoDB. To convert a MyISAM or other table type to InnoDB, use “ALTER TABLE table ENGINE = InnoDB”. It could take some time to rebuild the indexes on large tables. There are other considerations about the use of InnoDB – please consult the MySQL manual.
  3. If the tables used don’t support transactions, it’ll just fail silently. Bad times. I highly recommend using Firebug and Zend_Db_Profiler to monitor database queries during development (see http://framework.zend.com/manual/en/zend.db.profiler.html);

And of course, the source can be found here: http://www.stevehollis.com/2010/03/practical-nested-transactions-with-zend_db-and-mysql/

Zend Framework: Using Command Line Scripts

Posted on: Feb 25, 2010 by wenbert

Thanks to David Caunt for this very useful article.

The article shows us how to create command line scripts using Zend Framework components. This is very useful especially with the database stuff.

<?php
 
// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH',
              realpath(dirname(__FILE__) . '/../application'));
 
// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV',
              (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
                                         : 'production'));
 
require_once 'Zend/Application.php';
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/config.php'
);
 
//only load resources we need for script, in this case db and mail
$application->bootstrap(array('db', 'mail'));

Using it would be something like this:

$db = $application->getBootstrap()->getResource('db');
 
//do something!
$row = $db->fetchRow('SELECT * FROM something');

The source can be found here. Sorry for the copy-paste. This is so useful that I want to see the code every time I forget.

Thanks to Rob Allen for directing me to David Caunt.

How to Unit Test your Zend Framework Application

Posted on: Feb 17, 2010 by wenbert

I am trying to learn Unit Testing using Zend Framework. I have set up a test application called LyZend in Github. Supposedly, the application should be able to display artists, albums, and tracks.

The tests are found in: http://github.com/wenbert/lyzend/tree/master/tests/ I have follwed Matthew Weier O’phinney’s method of setting up the tests.

lyzend / tests / TestHelper.php

<?php
require_once 'TestConfig.php';
 
/*
 * Start output buffering
 */
ob_start();
 
/*
 * Set error reporting to the level to which Zend Framework code must comply.
 */
error_reporting( E_ALL | E_STRICT );
 
/*
 * Set default timezone
 */
date_default_timezone_set('GMT');
 
/*
 * Determine the root, library, tests, and models directories
 */
$root        = realpath(dirname(__FILE__) . '/../');
$library     = $root . '/library';
$tests       = $root . '/tests';
$models      = $root . '/application/models';
$controllers = $root . '/application/controllers';
 
/*
 * Prepend the library/, tests/, and models/ directories to the
 * include_path. This allows the tests to run out of the box.
 */
$path = array(
    $models,
    $library,
    $tests,
    get_include_path()
    );
set_include_path(implode(PATH_SEPARATOR, $path));
 
/**
 * Register autoloader
 */
require_once 'Zend/Loader/Autoloader.php';
//Zend_Loader::registerAutoload();
Zend_Loader_Autoloader::getInstance();
 
/*
 * Add library/ and models/ directory to the PHPUnit code coverage
 * whitelist. This has the effect that only production code source files appear
 * in the code coverage report and that all production code source files, even
 * those that are not covered by a test yet, are processed.
 */
if (defined('TESTS_GENERATE_REPORT') && TESTS_GENERATE_REPORT === true &&
    version_compare(PHPUnit_Runner_Version::id(), '3.1.6', '>=')) {
    PHPUnit_Util_Filter::addDirectoryToWhitelist($library);
    PHPUnit_Util_Filter::addDirectoryToWhitelist($models);
    PHPUnit_Util_Filter::addDirectoryToWhitelist($controllers);
}
 
 
/**
 * Setup default DB adapter
 */
/*
$db = Zend_Db::factory('pdo_sqlite', array(
    'dbname' => $root . '/data/db/bugs.db',
));
Zend_Db_Table_Abstract::setDefaultAdapter($db);
*/
 
 
/*
 * Unset global variables that are no longer needed.
 */
unset($root, $library, $models, $controllers, $tests, $path);

You might noticed that I included a TestConfig.php file above. Here is the file:

<?php
 
// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
 
// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));
 
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

Here is a sample test for my Artist Model.
lyzend / tests / application / models / ArtistTest.php

<?php
// Call Model_ArtistTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Model_ArtistTest::main");
}
 
require_once dirname(__FILE__) . '/../../TestHelper.php';
 
/** Model_Artist */
require_once 'Artist.php';
require_once 'ArtistMapper.php';
require_once 'DbTable/Artist.php';
 
/**
 * Test class for Model_Artist.
 *
 * @group Models
 */
class Model_ArtistTest extends Zend_Test_PHPUnit_ControllerTestCase 
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite("Model_ArtistTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }
 
    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
 
    public function setUp()
    {
        $this->bootstrap = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . DIRECTORY_SEPARATOR . 'configs' . DIRECTORY_SEPARATOR . 'application.ini'
        );
        parent::setUp();
 
    }
 
    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
    }
 
    public function testCanTest()
    {
        //this is a sample test
    }
}

The XML file is like this:

<phpunit>
    <testsuite name="Ly Test Suite">
        <directory>./</directory>
    </testsuite>
 
    <php>
        <!-- <ini name="include_path" value="../library"/> -->
    </php>
 
    <filter>
        <whitelist>
            <directory suffix=".php">../library/</directory>
            <directory suffix=".php">../application/</directory>
            <exclude>
                <directory suffix=".phtml">../application/</directory>
                <file>../application/Bootstrap.php</file>
                <file>../application/controllers/ErrorController.php</file>
            </exclude>
        </whitelist>
    </filter>
 
    <logging>
        <log type="coverage-html" target="./log/report" charset="UTF-8"
            yui="true" highlight="true"
            lowUpperBound="50" highLowerBound="80"/>
        <log type="testdox-html" target="./log/testdox.html" />
    </logging>
</phpunit>

Running the test would be something like this:

phpunit --configuration phpunit.xml

Matthew did not provide sample test for Mappers. So I created one something like this:

$mapper = new Ly_Model_ArtistMapper();
$this->assertTrue($mapper instanceof Ly_Model_ArtistMapper);

My process was like:

  1. Setup Unit Testing in Zend Framework
  2. Create tests (let’s say for Artist Model).
  3. Make code in my model to pass the tests.
  4. Repeat step 2 and then go to next model if satisfied.

FYI: I am not so sure about my Model. I am not sure if I am breaking any rules when I created them. It would be cool if you could check them out (http://github.com/wenbert/lyzend/tree/master/application/models/) and discuss my mistakes below.

Thanks!

Akra’s Zend Framework 1.10 Tutorial

Posted on: Feb 08, 2010 by wenbert

From Akrabat’s blog:

As a result, I have updated my Zend Framework tutorial so that it is completely current. The main change I made was to remove the _init methods in the Bootstrap as they are no longer needed. I also take advantage of the new features of the zf tool to enable layouts and create forms. It’s a shame that it gets the class name of the form wrong though!

HTML5 Canvas Tutorial

Posted on: Feb 08, 2010 by wenbert

The Paint Application from Mugtug.com is very impressive. It uses HTML5. Very responsive. I found it in HN and the hackers seemed to be impressed as well.

Around the web, people are already talking about HTML5 and Canvas as a replacement for Flash. Click here to read the Canvas Tutorial.

An example of an Object-relational Mapper in PHP

Posted on: Feb 05, 2010 by wenbert

Dennis Hotson posted in his blog a brief and good example of an ORM for PHP.

What is an Object-relational Mapper?

Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a “person object” with “slots” to hold the data that comprise the entry: the person’s name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain “phone number objects” and so on. The address book entry is treated as a single value by the programming language (it can be referenced by a single variable, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.

However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within normalized tables. The programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.

The heart of the problem is translating those objects to forms that can be stored in the database for easy retrieval, while preserving the properties of the objects and their relationships; these objects are then said to be persistent.

-Wikipedia

The full source code can be found in Github.

I’m sure this will come in handy as a reference in the future. Thanks to Dennis Hotson for sharing.

A Quick Update

Posted on: Jan 29, 2010 by wenbert

Hello All. Sorry for the few updates. I have not been doing any Zend Framework / PHP related work for over a month now. I am in Aurland, Norway for a training. I will be staying here for about three months. I will be back home on April 2010.

Right now, I am thinking of starting a new pet project. I have the initial specifications in my head and I will put it into writing when I have time.

I will have more updates and Zend Framework / jQuery / PHP / MySQL / web development related soon.

Thanks!

-wenbert

Excel-like Javascript Grid Editors

Posted on: Jan 19, 2010 by wenbert

Here is quick quote:

A short list of my favorite JavaScript grid components.
How many times did you hear users asking you: “something simple, a grid like excel”?

When I was a VB programmer, oh yes, I have this dark spot on my career, and it is not the only one… this request threw me in panic. Usually what your “killer” is asking you is not what you, programmer, are thinking of (namely the power of cell functions, programmability, graph etc., that probably your “killer” does not even imagine): what they are thinking about is the editor flexibility, the ability to add columns, rows, move cells blocks, copy and paste from different sources.

After the ritual pointing-out that your application is NOT Excel, the VB solution was to adopt the standard flexGrid or the mythical TrueDbGrid that made happy both the killer-user and the victim-programmer.

The source here: roberto.open-lab.com


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