Federated engine – MySQL table as symlink

db, development No Comments »

Are you aware of Federated engine in MySQL (apart from MyISAM and InnoDB)?

This engine allows you to define a table that sucks data from another table, even from a remore server. The tables definition must be the same.

I use it for the following:

  1. Every time I rebuild the project, I have wait for 15 minutes while two big tables are created and filled with data — these are geo data tables (world cities, regions, etc), 4 mln records, and POI table, 2 mln records. I use Federated tables to create two separate databases and just link these tables in my project.
  2. These tables are shared between several environments (dev, test and live) on the same server.

To check if your MySQL server has the Federated engine supported, you can use just a phpMyAdmin — go to home page of you phpMyAdmin installation (click Home picture), then choose Engines tab and check there.

If it’s not enabled (gray), open your my.ini file, find the “[mysqld]” part and make it to look like this:

[mysqld]
federated

P.S. If you have an error in the table definition, phpMyAdmin shows your database as empty. To fix this, log in via mysql console and try to make a SELECT from this poorly defined table and you get the error message to work with.

Currency exchange in your application

db, development, ideas, php, zend No Comments »

That’s easy, you need 2 things:

  1. Fresh currencies exchange rates
  2. Some way to excange amount from one currency to another.

This how I did it: get values from European Central Bank (ECB) for step #1 and wrote MySQL user defined function for step #2.

Here is how to export currencies rates from ECB (EUR is a base currency, and I add self rate as 1:1). First I create such database table:

CREATE TABLE IF NOT EXISTS `currency` (
  `code` char(3) NOT NULL DEFAULT '',
  `rate` decimal(10,5) NOT NULL COMMENT 'Rate to EUR got from www.ecb.int',
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Currency rates (regularly updated)';

Now let’s fill it with rates:

<?php

class CurrencyController extends Controller_Ajax_Action {

  public function importAction() {

    $db = Zend_Registry::get('db');
    $db->beginTransaction();

    $url = 'http://www.ecb.int/stats/eurofxref/eurofxref.zip?1c7a343768baab4322620e3498553b5a';
    try {
      $contents = file_get_contents($url);
      $contents = archive::unzip($contents);
      $contents = explode("\n", $contents);

      $names = explode(',', $contents[0]);
      $rates = explode(',', $contents[1]);

      $names[] = 'EUR';
      $rates[] = 1;

      for ($i = 1; $i < sizeof($names); $i++) {
        if (!(float) $rates[$i]) continue;
        $db->query( sprintf('INSERT INTO `currency`(`code`, `rate`)
              VALUES ("%s", %10.5f)
              ON DUPLICATE KEY UPDATE `rate`=VALUES(`rate`)',
             trim( $names[$i] ),
             trim( $rates[$i] )
        ) );
      }

      $db->commit();
    } catch ( Exception $O_o ) {
      error_log( $O_o->getMessage() );
      $db->rollback();
    }

  }
}

Now let’s create a SQL function for handy converts. Create a udf.sql file and add this in it:

DELIMITER //

DROP  FUNCTION IF EXISTS EXCHANGE;
CREATE FUNCTION EXCHANGE( amount DOUBLE, cFrom CHAR(3), cTo CHAR(3) ) RETURNS DOUBLE READS SQL DATA DETERMINISTIC
    COMMENT 'converts money amount from one currency to another'
BEGIN
    DECLARE rateFrom DOUBLE DEFAULT 0;
    DECLARE rateTo DOUBLE DEFAULT 0;

    SELECT `rate` INTO rateFrom FROM `currency` WHERE `code` = cFrom;
    SELECT `rate` INTO rateTo   FROM `currency` WHERE `code` = cTo;

    IF ISNULL( rateFrom ) OR ISNULL( rateTo ) THEN
        RETURN NULL;
    END IF;

    RETURN amount * rateTo / rateFrom;
END; //

DELIMITER ;

and run this command in your shell:

mysql --user=USER --password=PASS DATABASE < udf.sql

This is how you can use this function — how to convert 10 US dollars to Canadian dollars:

SELECT EXCHANGE( 10, 'USD', 'CAD')

which results in $10 = 10.93 Canadian dollars.

P.S. Consider adding the currency export action call to your cron scripts.

P.P.S. A function to unzip the data file can be got at php.net

Flash uploader and HTTP password protection

development, ideas, zend No Comments »

You are working on a project and you want to protect the beta version with password so that only allowed people (beta testers) could access it.

You decide not to invent the wheel and to use the standard HTTP authentication.

First idea is to use your Apache web server to do this, so you write something like that in .htaccess file:

AuthName "Private zone"
AuthType Basic
AuthUserFile /path/to/.htpasswd
require valid-use

This solution is simple and that’s why good.

A problem comes on stage when a Flash file uploader is added to your project – usually it cannot “login” to your site, i.e. users are not able to use the Flash file uploader behind beta login.

That’s how I solved it.

It’s not the web server who must solve this (Apache), it’s the application server (PHP). So remove the lines above from .htaccess and use Zend_Auth_Adapter_Http for this purpose — it’s Zend’s HTTP Authentication Adapter.

What concerns the Flash uploader: it sends ‘Shockwave Flash’ as value of ‘User-Agent’ request header. So in your Initializer or Bootstrap file (where you load Zend_Auth_Adapter_Http) check this header value, and if it’s not Flash’s, go for HTTP authentication.

P.S. Hackers can assume this and fake the header to access your site. To cope with that, use an additional secret request variable (Flash uploaders allow this) and check it at server side.

Reverse Geocoding

development, geo 2 Comments »

Reverse Geocoding is process opposite to Geocoding (when you get map coordinates by city/country given). So the idea is to get city name by coordinates on the map.

Why you may need it? For example, user is supposed to add a marker on the map, and you want to check that the marker is within a particular country or region.

Solutions:

  1. Google GeoCoder (JavaScript) can work with coordinates to retrieve location name. Advantage is that return information is translated to the preferred language of your browser. Here is an example you can play with.
  2. GeoNames.org offers several services, among which you can find Reverse Geocoding web service (REST or JSON) which can work with coordinates and postal codes. Advantage — you can download city/region/country names and POI with coordinates.

GeoNamesBy the way, here are results of benchmarking Google vs. GeoNames.

XML to CSV conversion

db, development, ideas No Comments »

MySQLData feeds often come in XML format, so your application must be able to deal with that format.

As I already wrote, data in CSV format (comma separated values) can be loaded to database extremely fast. So my idea was to convert XML data files to CSV and then use bulk load to database. My tests shown that this is faster in 10-100 times than one by one inserts.

Yesterday I decided to write a generalized solution for this, and it turned out that there is no need: it’s just coming — MySQL 6 will have such feature!

How it works: you create a table, name its columns exactly as XML nodes/attributes names or — and MySQL server will load it correspondently.

Example — you downloaded a POI list file (Points of Interest) called poi.xml that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<gpx>
    <wpt lat="58.691931900" lon="11.253125962">
        <name>Parking</name>
    </wpt>
    <wpt lat="58.315525000" lon="12.305828000">
          <name>Fast Food Restaurant:Max i trollhattan</name>
    </wpt>
    <wpt lat="57.717958100" lon="11.880860600">
          <name>Picnic spot</name>
    </wpt>
</gpx>

You create a MySQL table:

CREATE TABLE IF NOT EXISTS `poi` (
  `lat` varchar(255) NOT NULL,
  `lon` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL
) DEFAULT CHARSET=utf8;

OK, now you load the XML data to your table:

LOAD XML INFILE '\\path\\to\\poi.txt'
INTO TABLE `poi`
ROWS IDENTIFIED BY '<wpt>'

Voila!

The good thing is that MySQL 6 is already available in alpha version — good enough for development purposes; I gave it a try — it takes 5 seconds to load 4.8 Mb of data in 19 files.

Setting the file access permissions for files and folders

development, server 1 Comment »

You have a web application hosted on a server and you want to set file access permissions by chmod command, different for files and folders.

Why different? A folder must have ‘x’ (access) flag:

drwxr-xr-x

At the same time a file shouldn’t have it (otherwise it would be executable):

rw-r--r--

How can you set it up for all nested files/folders in your application folder?

You can solve this task by setting common persmissions for all files and folders (step 1) and then make folders accessable (step 2), recursively:

chmod -R 644 .
chmod -R a+X .

But chmod allows you to set up only access flag for folders, you cannot set one persmission for folders and another for files.

Here is a script written by my collegue Anton [vojtoshik] Voitovych to solve this task.

Copy it and save to a file (I saved it in /bin/rchmod — thus it’s accessable for all users of my system):

#!/bin/bash

files="0644";
directories="0755";

path=$1;
shift;

while getopts "d:f:" OPTION
do
case $OPTION in
f) files="$OPTARG" ;;
d) directories="$OPTARG" ;;
esac
done

if [ "$path" != '' ]; then
    find "$path" -type d ! -name "." -exec chmod "$directories" {} \;
    find "$path" -type f -exec chmod "$files" {} \;
else
    echo "Usage: rchmod <path_to_directory> [-d <directories mode>] [-f <files mode>]";
    echo -ne \\n;
fi

OK, now make it executable:

chmod 755 rchmod

How to use it.

1. You are in your application folder and want to set 755 (drwxr-xr-x) mode for folders and 644 (rw-r--r--) mode for files which is the default:

rchmod .

2. You want to set 123 permissions only for folders in a particular folder::

rchmod /some/path/to/folder -d 123

3. You want to set 123 permissions for folders and 456 permission for files in a particular folder::

rchmod /some/path/to/folder -d 123 -f 456

Note: don’t forget that every time after that command run you should make some folders writable (wp-content/uploads, cache, temp — what else you have in your webapp).

Zend Auth Session Expiration Time

development, php, zend No Comments »

After authentication in my project it takes about 10-20 minutes for the auth session to expire, which is not handy — you go to get a snack and see a login screen coming back.

This is how to make the TTL of your auth session longer:

$s = new Zend_Session_Namespace(
    $this->_auth->getStorage()->getNamespace() );

$s->setExpirationSeconds( strtotime('30 day', 0) );

Now your users will log in for 30 days.

You can call this code in your login action after successful authentication and before the redirect to the landing page.

Sharing work between agents

db, development, ideas, php No Comments »

There are situations when you need to separate processing of big amount of data between several “agents”, e.g.:

  • you have a long list of websites which must be checked for being alive (404 error check) by your web-clawlers;
  • a queue of photos to be resized or videos to be converted;
  • articles that your editors must review;
  • catalogue of blog feeds that your system must import posts from;
  • etc.

The idea to do this is simple:

  1. Give a small piece of big work to an agent.
  2. Mark this piece as given to him (so that none other starts to do the same job) and remember the time stamp when the job was given or when the job becomes obsolete (this agent is dead, let’s give this job to someone else).
  3. If work is done — go to step #1.
  4. After some period of time (1 hour) check all the time stamps, and if some agents didn’t cope with the job, mark the jobs as free so that others could start to work on it.

The problem is between steps #1 and #2 — while you gave a job to Agent 1 and going to mark it as given to him, what if Agent 2 is given by the same job? If you have many Agents, this  can happen at real. This situations is called concurrent read/write.

To overcome this a lock can be used.

In this article I wil explain, how to use locks in Zend project with MySQL database.

First of all, MySQL documentation tells that SELECT .. FOR UPDATE can be used for that purpose. First step is to select records by that statement, and second step is to mark them as locked. Requirements are to use InnoDB storage and to frame these two statements in a transaction.

Happily, Zend_Db_Table_Select has a special method forUpdate() that implements SELECT .. FOR UPDATE statement. Zend_Db can cope with transactions as well. Let’s try it!

To lock a record, we need two fields:

  1. one to remember ID of agent that is processing this record (let’s call this column ‘locked_by‘)
  2. one another to know the time when the lock becomes obsolete (let’s call this column ‘expires_at‘)

I wrote a  class that inherits from Zend_Db_Table and helps to get records with locking them.

<?php

class Koodix_Db_Table_Lockable extends Zend_Db_Table
{
    protected $_lockedByField = 'locked_by';
    protected $_expiresAtField = 'expires_at';
    protected $_TTL = '1 HOUR'; //time to live for lock

    public function fetchLocked( Zend_Db_Table_Select $select,
        $lockerID ) {

        $db = $this->getAdapter();
        $db->beginTransaction();

        $column = $db->quoteIdentifier( $this->_lockedByField );
        $select->forUpdate()
             ->where("$column=? OR $column IS NULL", $lockerID);

        $data = $this->fetchAll($select);
        if( empty($data) ) return null;

        $expiresAt = new Zend_Db_Expr('DATE_ADD( NOW(),
            INTERVAL ' . $this->_TTL . ')');
        if( sizeof($this->_primary) > 1 ) {
            foreach( $data as $item ) {
                $item->{$this->_lockedByField} = $lockerID;
                $item->{$this->_expiresAtField} = $expiresAt;

                $item->save();
            }
        }
        else {
            $arrIds = array();
            foreach( $data as $item ) {
                $arrIds[] = $item->id;
            }

            $this->update(
                array(
                    $this->_lockedByField => $lockerID,
                    $this->_expiresAtField => $expiresAt,
                ),
                $db->quoteIdentifier(current($this->_primary)) .
                    ' IN ("'.implode('","', $arrIds).'")'
            );
        }

        $db->commit();
        return $data;
    }

    public function releaseLocks( ) {

        $column = $db->quoteIdentifier( $this->_expiresAtField );

        return $this->update(
            array(
                $this->_lockedByField => null,
                $this->_expiresAtField => null,
            ),
            "$column <= NOW()"
        );
        ;
    }
}

If the table has a composite primary key (containing more than one column), the ActiveRecord approach is used, so the save() method for every record is called, that’s simple (drawback — multiple update queries). Otherwise, if it is a deep-seated table with one ID column as a primary key, then the IDs are collected in a list and all records are updated by a single statement with IN in where clause (which is much faster).

TTL (‘Time to Live‘) — period of time when lock is allowed. In my application the default is one hour. Format of TTL can be seen in MySQL documentation.

And now how to use it.

Let’s imagine you have several editors that divide the big articles list and review them. My model class has a method fetchForUser() that returns no more than 5 articles for current user (by given user ID).

This is an Article table model, inherited from the class above. Usually such classes are located at

application/default/models/ArticleTable.php
<?php
class ArticleTable extends Koodix_Db_Table_Lockable
{
    protected $_name = 'article';

    public function fetchForUser( $userId, $count=5 ) {

        $select = $this->select()
            ->where('reviewed = 0')
            ->order('expires_at DESC')
            ->order('date_imported DESC')
            ->limit( $count );

        return $this->fetchLocked($select, $userId);
    }
}

Note: if the editor refreses the page, the expres_at fields is refreshed by current time as well.

As for step four of our algorithm (releasing all obsolete locks) — create an action in your backend controller, call your table model releaseLocks() method in it and call that action periodically by Cron.

To boost the performance of the lock releasing, create an index on the expires_at column. (Because of this reason I rejected the ‘locked_since‘ column in favor of ‘expires_at‘)

P.S. In my database date/time columns have DATETIME type. If you use INT to store timestamps, convert it to unix time and back.

assembla.com – free development tools

assembla, development No Comments »

All sources for my development projects I store at assembla.com — very cool service for dvelopers, offering both free and paied services.

assembla

Free users have almost the same services scope just limited by space:

  • projects (in free plan the source is open for anyone), milestones and tickets
  • SVN/Git repository (you can close/refer tickets by commit messages)
  • wiki with several mark-up languages
  • team collaboration tools
  • agile tools

I started from hosting files of my FireFox addons there — SVN and wiki make it perfect choise.

Then I got used to the handy and comfortable interface so much that became a paied user — for xUSSR person it’s worth mentioning :)

And the last but not the least — Assembla team is very open and keeps in touch with their users.

Several sites on single WordPress installation

development, ideas, php, wordpress 3 Comments »

I have a couple of other WordPress blogs on the same server besides this one. One day I realised that all of them have 3 different WP versions and, as result, different admin areas which is not handy. I decided to make them use the same WordPress installation.

Ok, first of all, I deleted wp-admin and wp-includes folders and created new ones as symbolic links. Though the frontend worked well, I couldn’t log in into admin area, because the browser was redirected to that blog which was the base for all the rest for unknown reason.

The investigation shown, that admin area of WordPress is a separate sub-application, thing in itself, and in my case it resolves the absolute path to its source as the path to the base blog. I wanted each blog to use its own folder because there are config file and uploads folder.

It took me some time to find a solution. It requires two steps.

First, I added this line to the top of the .htaccess to make any PHP request to the blog (the blog front-end and the admin area scripts) call the same script before thier start:

#fix for several sites on the same WP installation
php_value auto_prepend_file "/var/www/site_doc_root/prepend.php"

In this code /var/www/ is the root folder for all my sites, and the site_doc_root is the document root of the current site (folder where all its files are located).

OK, the 2nd step — the contents of the prepend.php script. It is easy — it just must define an absolute path constant which is used all around the WordPress:

<?php
define('ABSPATH', dirname(__FILE__).'/');

OK, after that I decided not to use one of the blogs as source for others, but download a fresh copy of WordPress and make it a source of the symbolic links for all my blogs. This helps to update them.

Then I deleted wp-admin and wp-includes folders and some wp-files and recreated them as symlinks. Attention to wp-config.php — don’t delete it, keep it unique for every site!

To make this task easier, I created setup.sh file, pasted the contents I show below, run this command

chmod 755 setup.sh

then I copied it in every site folder and launched there for every site:


ln -s /var/www/wordpress/wp-admin wp-admin
ln -s /var/www/wordpress/wp-includes wp-includes

ln -s /var/www/wordpress/wp-app.php wp-app.php
ln -s /var/www/wordpress/wp-atom.php wp-atom.php
ln -s /var/www/wordpress/wp-blog-header.php wp-blog-header.php
ln -s /var/www/wordpress/wp-comments-post.php wp-comments-post.php
ln -s /var/www/wordpress/wp-commentsrss2.php wp-commentsrss2.php
ln -s /var/www/wordpress/wp-config-sample.php wp-config-sample.php
ln -s /var/www/wordpress/wp-cron.php wp-cron.php
ln -s /var/www/wordpress/wp-feed.php wp-feed.php
ln -s /var/www/wordpress/wp-links-opml.php wp-links-opml.php
ln -s /var/www/wordpress/wp-load.php wp-load.php
ln -s /var/www/wordpress/wp-login.php wp-login.php
ln -s /var/www/wordpress/wp-mail.php wp-mail.php
ln -s /var/www/wordpress/wp-pass.php wp-pass.php
ln -s /var/www/wordpress/wp-rdf.php wp-rdf.php
ln -s /var/www/wordpress/wp-register.php wp-register.php
ln -s /var/www/wordpress/wp-rss.php wp-rss.php
ln -s /var/www/wordpress/wp-rss2.php wp-rss2.php
ln -s /var/www/wordpress/wp-settings.php wp-settings.php
ln -s /var/www/wordpress/wp-trackback.php wp-trackback.php
ln -s /var/www/wordpress/xmlrpc.php xmlrpc.php

That’s not all ;)

I decided to update my WordPress installation every one or two months.

To do that, in the /var/www/ folder (where all my sites reside) let’s create an update script update_wordpress.sh with the following contents:

wget --timestamping http://wordpress.org/latest.zip
unzip -o latest.zip

This will download a fresh copy of the wordpress if it’s changed (though wordpress team doesn’t show the file Last-Modified header, I think one day they will) and unzip it to /var/www/wordpress/ folder which is the source for our symlinks.

Yes, you got it right — launching this script is all I need to update all my blogs.

Let’s make it periodic:

crontab -e

and then add this line to run the update process automatically every 1st day of every month at 9 AM:

0 9 1 * * /var/www/update_wordpress.sh > mail -s "Wordpress updated" your@email.com

P.S. Of course, SVN checkout can be used for that purpose :)

Documents in repository

development No Comments »

I rent a server in a data center. Why not to use it also for storing my documents in SVN repo?

Advantages:

  • the access from anywhere — home and work, and forget about flash card.
  • SVN client can show changes even for Microsoft Word documents
Drawbacks:
  • a server must be in place. I already have it, so why not to use it.
  • an SVN client must be installed at every machine where I going to work with the documents. However, if I just need to read it, there is a web interface to download it.

What more can you get from bug tracking?

development No Comments »

Some thoughts about bug tracking.

Low priority bugs

Leave low priority tickets for new comers — such bugs let you show internals of your product doing something useful. Among such issues are all simple kinds of work with text (for example, fixing typos).

Underestimated issues

Find the issues that have required much more time than it was estimated (2-3 times and more) — it can mean, that the developer who worked with it faced something unusual, so he can share the experience gained with the rest of the team.

Bugs on paper

Make sure you (or your developers) don’t keep a list of bugs to fix on the sheet of paper. We do it due to the fear of appearing as non productive developers, right? Just don’t do this. Report them.

Developer ratio

There are plugins to bug tracking systems (I saw such one for Jira) that calculate under/over-estimate ratio for every developer, i.e. how much is the difference between the estimate and actual spent time amout. This ratio is multiplied by all further developer’s estimates, so that his manager can find out how much the real estimate is (most adequate developers have this ratio equal to 1, of course). If you show the ratios to the developers, their estimates could become more accurate.

By the way, do you know that Jira appeared in Star Wars? :)

RSS feed of error log

development, ideas, php No Comments »

Your PHP application logs every error to error log. Do you want to keep track of them in your favourite Feed Reader? Then follow up reading this article!

First of all, you must tell to your application to log errors to a log file. Two parameters must be set: what to log and where to save it. First can be done by error_reporting setting, second — by setting error_log PHP value:

error_reporting( E_ALL & ~E_NOTICE ); //all except notices
ini_set( 'error_log', 'temp/error.log' );

Put it in the beginning of your application, for example, at the top of index.php file.

By the way, you can write something custom in the error log by calling error_log function:

error_log('something');

OK, now, how to make a feed from your error log.

You can do this in a few ways.

First, let’s do it manually.

Manual solution

1. Remove ini_set setting described above. Then create .htaccess file in the top folder of your application and place this line in it:

php_value error_log temp/error.log

It will tell to all scripts of your application to take this setting into consideration without manual calling of ini_set function.

2. Create feed.php file. Place this line inside it:

$contents = file_get_contents( ini_get( 'error_log' ) );
echo nl2br( $contents );

It’s dirty for now, but enough as a check.

3. Make sure that your error log file is not empty. Now you can access your feed.php file via browser and check that it’s showing you the contents of your error log.

4. Now you should create an RSS feed from contents of the file. You can rely on your framework or use a custom solution, e.g. download EasyRSS class and fill the contents of the feed with data from the error log (you would need to think about regexp to parse date and error text from it).

After that you could feed your feed reader with the feed address ;]

Ready-made solution

Download a ready PHP class that will do all it for you — RSS Feed. Yes, it’s simple. You can even protect your feed with a password.

Notes:

  • on the production server change your error_reporting value, for example, to log fatal errors only.
  • log errors in the catch() part of the exception handling mechanism:
    try{ ... }
    catch(Exception $e) {
      error_log( $e->getMessage() );
    }

Quick CSV import with visual mapping

development, php, php classes 101 Comments »

Several years ago I created PHP class Quick_CSV_Import to import CSV files to a database table very quickly (LOAD DATA INFILE statement). I found that the class became quite popular in India due to feedback received :]

Now I want to share a little application on the basis of that class.

Quick CSV Import with Mapping” is a PHP example application that imports CSV file to a database table with visual mapping of CSV columns to table columns.

CSV Mapping Master - click to download

Of course, you can get a copy of the application source – just go to the SVN repository.

Don’t forget to send me your feedback and donations ;]

P.S. If you are having problems with going to step 2 while using the app, try the following:

  1. Open Quick_CSV_import.class and find “LOAD DATA INFILE
  2. change it to “LOAD DATA LOCAL INFILE

It’s connected with permissions at your Linux server. Thanks to Noel for the solution.

Delete Your Code #1: time calculations

delete your code, development, php No Comments »

You can be (rich and healthy) or (poor and ill).

You can have (readable and laconic code) or (confusing one).

Oh no, I’ve said too much. I haven’t said enough” © REM. The following two examples do the same – so choose any ;]

echo time() + (60 * 60 * 24 * 14); //14 days from now
echo strtotime( '14 day');

Second variant also allows things like ‘-2 years‘.

Want the same in MySQL? Not a problem:

SELECT DATE_ADD( NOW(), INTERVAL 14 DAY )

Delete Your Code #0: Timestamp

delete your code, development 1 Comment »

In many cases your application must keep track of an entity creation or update time. Do you know, that this can be done automatically?

Yes, I know, there is such feature out of the box in many frameworks (for example, Symfony). Naming convention guaranties that database table’s column named ‘stamp_created‘ will be set by entity creation date, and ’stamp_updated” – by time when any column of the entity has been changed. This done by application server side code (e.g. PHP).

The same can be done by good database table defenition (in MySQL).

  • Create a TIMESTAMP column with CURRENT_TIMESTAMP as default – and that’d be an auto-initializing ‘stamp_created field. 
  • Create a TIMESTAMP column with ON UPDATE CURRENT_TIMESTAMP  directive – and that’d be an autoupdating ‘stamp_updated’ field. 

Other options can be found in MySQL manual.

All this can be done in PHPMyAdmin application by correspondent settings. 

Drawback of such solution: table cannot have both ‘stamp_created’ and ‘stamp_updated’ fields – choose one pill, Neo.

Phonetic won!

development, php, php classes 5 Comments »

winner1.gif align=Yes, my class Phonetic won the first place of the PHPClasses Innovation Award.

Thanks to everyone voted for me!

You can check a demo here.

Vote for Phonetic class

development, php, php classes 1 Comment »

My PHP class Phonetic is nominated on phpclasses.org Innovation Award.

Vote for it!

The class generates words that phonetically are equal to the given one, but are written differently.

Get Mozilla FireFox T-Shirt

development, FireFox 3 Comments »

FirefoxDo you want to get a Mozilla Add-ons Developer T-shirt?

Recently I have received an email from Mozilla:

If you are able to achieve Firefox 3 beta 3 compatibility by March 18th on addons.mozilla.org, you are eligible for a Mozilla Add-ons Developer T-shirt. If you have updated your add-on, and would like a shirt, please fill out the following form:

https://addons.mozilla.org/en-US/firefox/developers/tshirtrequest

Additionally, if your add-on is one of the top 50 most used add-ons by Firefox 3 users on the Firefox 3 release day, Mozilla will offer to sponsor (for an amount we will determine) a party for you and your friends. That is, Mozilla will chip in for you and your friends to celebrate your tools success! Mozilla will be in contact with the top add-ons shortly after the Firefox 3 release.

As for me, I have created a Get File Size plugin, and as soon as I did it, I have become eligible to fill a shipping form.

Here is a couple of links to help you on this way:

It is a good chance to make your cool plugin idea come true.

I’m here to delete code

delete your code, development 1 Comment »

I have only made this letter longer
because I have not had the time to make it shorter

Blaise Pascal, Lettres provinciales.

What do you think you are supposed to do as developer? To create code? Nope. To delete it!

delete_eraser1.jpgHave you ever thought why it takes 5-15 minutes to get into the flow? From my point of view, that’s because you have to understand the root of a task, to load its code base into your operating memory – brain. So the less code you have to deal with, the more productive you are in juggling with it.

Alongside this fact consider these statements:

  • Less software is easier to manage.
  • Less software reduces your codebase and that means less maintenance busywork (and a happier staff).
  • Less software lowers your cost of change so you can adapt quickly. You can change your mind without having to change boatloads of code.
  • Less software results in fewer bugs.
  • Less software means less support.

( Getting Real :: Less Software chapter )

At the same time it’s funny how often I got more robust code by moving from 100 lines to 10…

In the next post I will describe the ways I use to achieve that goal.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in