Delete Your Code #2: less OOP visibility keywords

delete your code, development, ideas, php Comments Off on Delete Your Code #2: less OOP visibility keywords

Hey! I gonna describe tricks that I use to have less code. Why it is important to have less code, you ask? Less code means less bugs, less support, less developer brains waste.

Today’s trick is extremely simple — when you have a long set of public, protected or private class properties, remove the visibility keyword set to each declaration but define it once as comma separated declaration.

Same applies to class constants as well.


// Before:
class Cat {
    const KINGDOM = 'Animalia';
    const PHYLUM  = 'Chordata';
    const FAMILY  = 'Felidae';

    public $tail;
    public $whisker = '\/';
    public $head;
    public $legs = array(1,2,3,4);

// After:
class Cat {
        KINGDOM = 'Animalia',
        PHYLUM  = 'Chordata',
        FAMILY  = 'Felidae';

        $whisker  = '\/',
        $legs = array(1,2,3,4);

One benefit is that the code looks clear and it’s much easier to scan rather then to read.

Second benefit is when you need to change the visibility for a property, you don’t have to edit the visibility keyword near the property name (which might be an error prone process when you are tired) — you just move the line up or down, which usually has a shortcut in IDE.

Known disadvantage is that most documenting engines don’t support this ferature.

6 points against writing an own CMS

development, ideas Comments Off on 6 points against writing an own CMS

Once upon a time I was asked at my job to work on company website. There was a choice among existing CMS for the website to be driven by, plus I could think about implemention of something of my own — but you know what? I didn’t feel comfortable to start a CMS from scratch. Now I know why, exactly.

I found this nice article called Homebrew CMS (by Seth Gottlieb), which lists six points of a modern content management system which you as architect should consider before a start:

  1. Versioning — it makes data model much more sophisticated;
  2. Localization — should images be translated, what is your default language, etc;
  3. Preview — the content being previewed must be connected with all the website and not visible to others;
  4. Deployment — dependency management like images which are pasted in the content;
  5. Usability — is probably the most common reason why companies abandon their home grown CMS;
  6. Access control — your system must control not functions only, but also the data.

All in all, an open source free CMS might be the best choice for you too. Spare your energy for something else.

Web application check list: geo data

development, ideas Comments Off on Web application check list: geo data

Things you would likely to check in your application. First story is about geo and localization features of your application.

  1. Detect browser languages, find the one your application supports and set it as your application’s current languages. If it’s not set, first auto-detect country (see below) and then use the country’s main language.
  2. Auto-detect country: first by IP (free database of countries IP addresses can be downloaded here), then by browser locale (en-US means it’s a USA user), then by auto-detected language (ru language gonna mean Russia. Yes, the user can be located in Ukraine or Belarus, not in Russia – but let’s face it, it’s much closer than nothing).
  3. On the grounds you’ve detected the country, you can preset the currency for the user.
  4. Save this data in user’s profile when he/she registers in your application. If your application cares about other languages the user can speak, you can parse the rest of browser languages and save them too.
  5. If entities of your application can be located on map, set geo meta tags to tell the search engines about place your entity is at. (success story). Find out more on geotagging at Wikipedia.

List of countries with a set of supported languages and default currency code for each one can be got from GeoNames (countries info dump).

Tech improvements would be funny to have

fun, ideas Comments Off on Tech improvements would be funny to have
  • a password field with auto-suggest feature
  • a message telling you that ‘Such password is already taken‘ (especially indicating by which user)
  • a authentication system that recognizes you not by the username and password you’ve typed, but by the speed of typing and delays between characters
  • case sensative domains names
  • a hyper link, that opens multiple windows when clicked
  • a page advert analyzing your face via webcam and rotating banners when you blink
  • porn sites that capture the video of you via your webcam while you surf them (maybe it exists already? beware!)

Open source project as a CV

development, fun, ideas, marketing Comments Off on Open source project as a CV

I think it’s a nice idea to contribute to open source project at least to just highlight this fact in your CV/resume when you are looking for a job.


  • you show your level of commitment to something
  • money is not the only motivator for you
  • the code written by you is publically visible — you don’t need to explain what major design patterns you know, which technologies you are familiar with and how good you usually polish your code, that all can be seen

I think it can be compared with marriage. Remember that Alec Baldwin quote  from “The Departed” movie?

Marriage is an important part of getting ahead: lets people know you’re not a homo; married guy seems more stable; people see the ring, they think at least somebody can stand the son of a bitch; ladies see the ring, they know immediately you must have some cash or your cock must work.

10 reasons not to use Assembla

assembla, development, ideas 3 Comments »

Although Assembla is one of the best ticket systems, I hate it at times. Main reason is that their team plays with fonts and colors and thus changes the site appearence, and at the same time ignores the major issues.

Here is the list that irritates me the most:

  1. When you create a ticket, the editor doesn’t work properly. For example, if you hightlight a URL with intention to mark it as a link, they still ask you for the URL in a prompt (a month ago they would even just replaced it with a default markup text like “[[ | URL TEXT]]“)
  2. The same is WIKI based on tinyMCE — it fails so often, that 50% of times I have to open the content HTML source and fix things manually
  3. Affiliate system — it pays you back only if you refered 3+ new users. I have just 2 leads, and I loose $80 every month…
  4. Some time ago they had an offer to blog about them and get $5 reward — I wrote a post, and their marketing guy Ryan told me that they gonna pay me only after a referal would pay a bill — which was not mentioned in the offer.
  5. If you want to export tickets data (for example, to count some stats regarding development performance), you will have to deal with their internal semi-JSON format with no documentation (only not-so-self-explanatory feilds names)
  6. Previously they had a project name in project space URL, now they use a unreadable hash — if you work with more then 1 project, you’d feel how unhandy it is
  7. There are 3 (three!) different SVN repositories types (SVN+Trac, External SVN, Source/SVN) in Tools which is confusing. Every one has its own set of possibilities — you have to choose what is more vital for you, you cannot have it all.
  8. Current filter choise is lost if you leave Assembla page for 5-10 minutes, and you have to switch to it over again. The choise is saved in a HTTP-secure cookie (it means you cannot change it by JavaScript). Damn, why?
  9. They don’t show hours total for tickets  no matter how you group them. It’s one of the most important things for developers, guys.
  10. If you want just to get content of the project, you cannot.  I mean not SVN Checkout, but kind of SVN Export — download all folders/files without SVN client. They had a button that allowed to download the project as ZIP archieve, but now it’s not there. I have a few PHP projects which many people download and use, and they complain often about this missing feature.

All in all, Assembla still has a big way to go to maturity.

UPDATE [Feb 7, 2012] – previously, when you click on a milestone name on a ticket page, you go to the milestone and can see all tickets. Now you get the ugly build-in JavaScript prompt to rename the milestone. WAT?!%$??

MySQL Proxy

db, development, mysql Comments Off on MySQL Proxy

At times it’s necessary to know which queries the server runs right now.

Of course, you can try this statement:


but if you need a more poweful tool, try MySQL Proxy.

Although it’s still an alpha version, it’s a handy tool to monitor, filter and manipulate your queries since there is Lua scripting language interpreter supported which is quite obvious in usage.

The MySQL Proxy (as can be understood from its title) can help you to see communication between a few MySQL servers and a few clients.

My usage pattern is that the Proxy listens to 4040 port on my local machine, and if I change the port setting in connection string of any application (my job project or even PhpMyAdmin), I can see the queries logged in a console window.

You can track lots of characteristics of queries — just take a look at example Lua scripts in the package that you’ve downloaded.

Bulk SQL loading

db, development, ideas, mysql Comments Off on Bulk SQL loading

If you want to load a list of SQL files into your database on Windows, you can create a .cmd file with such content and run it.
Place it in the same folder where your .sql files are.

@echo off
SET DATABASE=my_database

FOR /F "usebackq" %%i IN (`dir /on /b %FORMAT%`) DO echo %%i && mysql --user=%USER% --password=%PASS% --default-character-set=utf8 %DATABASE% < %%i

Make sure, mysql command can be run. If no, either set the full path to mysql command tool, or add the path to PATH environment variable.

Sphinx pre-query not inheriting

db, sphinx Comments Off on Sphinx pre-query not inheriting

Sphinx is a nice search engine and is used at our project hugely.

Although, I found a case when using a pre-fetch query is not obvious. The pre-fetch query is a query that is run before the data is got from database, so thus you can set character encoding, tune database caching, set variables, etc.

So, if we have 2 sources, one is parent for all other sources since it has database connection params, and second one inherits from the parent.

source www {
    type                    = mysql

    sql_user                = root
    sql_pass                = 

    sql_query_pre           = SET NAMES utf8    

source www_country : www {
    sql_query = SELECT * FROM country

All works fine – when www_country souce is used, the same sql_query_pre will be used because www_country is a child of parent source.

Although, if one day you decide to add a custom pre-query to the child source, it seems you loose the parent’s ones:

source www_country : www {
    sql_query_pre = SET @usefulVariable = 1

    sql_query = SELECT * FROM country 

In this case it seems you have to duplicate the parental pre-query in every child =(
So the right child is gonna be:

source www_country : www {
    sql_query_pre = SET NAMES utf8    
    sql_query_pre = SET @usefulVariable = 1

    sql_query = SELECT * FROM country 

Reverse geocoding in your app

db, development, mysql 1 Comment »

Reverse geocoding is a process of getting toponym name (city name) by its coordinates.

To make this, you can use a remote service like I have already described, or implement it yourself.

To do so you need two things:

  1. A database of cities with coordinates (having a population value at least for major cities is a big plus)
  2. A method to find a closest city

#1 is left for you, let’s talk about #2.

In the previous post I introduced the DISTANCE function (SQL) to count a distance between 2 points by coordinates. Let’s use it to find the biggest city closest to a given point:

    COMMENT 'Finds a city by coordinates given. Returns City ID.'
    DECLARE d DOUBLE DEFAULT 0; /* useless var */
    SELECT id, DISTANCE(`lat`, `lng`, latitude, longitude) AS dist
    INTO cityID, d
    FROM `geo_cities`
    WHERE lat BETWEEN FLOOR(latitude - 0.5) 
                  AND CEIL(latitude  + 0.5)
      AND lng BETWEEN FLOOR(longitude- 0.5)
                  AND CEIL(longitude + 0.5)
    HAVING dist < radius
    ORDER BY IF(population > 0, population, 1) * (1/IF(dist > 0, dist, 1)) DESC
    LIMIT 1;
    RETURN cityID;
END; //

Well, this function orders cities by (population and distance) function — so that the biggest closest city is returned.

WHERE clause is supposed to shorten the number of cities which are looked through; otherwise we would have to search through whole world’s cities. In my solution the search is limited by a reasonably small rectangle.

In the next post I’ll tell you how to find a biggest city depending on current Google Maps zoom, so that it won’t give you a small city near Paris if you click on France at a world-level map view.

SQL function to count distance between two points

db, development, mysql 4 Comments »

Useful function.



    COMMENT 'counts distance (km) between 2 points on Earth surface'
    DECLARE dtor DOUBLE DEFAULT 57.295800;

    RETURN (6371 * acos(sin( lat1/dtor) * sin(lat2/dtor) +
        cos(lat1/dtor) * cos(lat2/dtor) * 
        cos(lon2/dtor - lon1/dtor)));
END; //


In next post I will explain how I used this function to implement a reverse geocoding — it’s useful when you need to find a closest city by given coordinates.

Sphinx on Windows and error 1067

development, php, server 1 Comment »

I attempted to setup Sphinx on Windows, but was not trivial — problem was that I couldn’t run the SearchD as a Windows service since I got 1067 error (“Process Terminated unexpectedly“).

It’s not obvious but helpful to know how you can get the error message the service crashes with. To do so, go to Control panel → Administration → Event Viewer. Here you can get all notices and error messages that the service produces:

If you get your service running and search tool gives you the correct results, but your PHP application gets FALSE as query result, try to see what SphinxClient’s getLastError() method returns:

$s = new SphinxClient;
$s->setServer("localhost", 3312);
$result = $s->query('test');
echo $s->getLastError();

In my case there was a following message:

searchd error: 
  client version is higher than daemon version 
  (client is v.1.22, daemon is v.1.19)

Preferrable sorting in MySQL

db, development, mysql Comments Off on Preferrable sorting in MySQL

At times, some records in a recordset are more important than others — e.g. a featured product in a products list. In such a case you can make 2 requests to get the featured item first, then to load other N-1 items, and then display them.

If you want to make it by one move, you can use a feature of preferrable sorting — you can define what value and in which field goes first if such value is present.

For instance, you want to show an item with item_id=15 first:

FROM items 
ORDER BY item_id IN (15) DESC

Which returns something like (featured item goes first):

| item_id  | name       |
| 15       | Product 15 |
| 32       | Product 32 |
| 31       | Product 31 |
| 30       | Product 30 |
| 29       | Product 29 |
| ...      | ...        |

Interview with Matt Mullenweg, the WordPress creator

wordpress 1 Comment »

How did the idea to create WordPress come to you and why did you decide to make it a free product?

Matt MullenwegWordPress evolved out of my own desire for a blogging product to make my site better, and a frustration with the existing solutions that I felt were too complicated and hard to use. WordPress was built on the code of an existing GPL product called b2, so it was completely natural for it to continue the GPL license and preserve the freedoms of our users.

How do you make money on it now and what do you plan in the future to earn more?

About 5 years ago I founded a company called Automattic to create commercial services around WordPress that would help grow the market. The first of these was an anti-spam service, Akismet, and we later followed up with, Gravatar, Polldaddy, IntenseDebate, VideoPress, VaultPress, and more to come.

How does your development process work: how many developers do you have, are they full/part time workers, are they located in an office (where?) or are they remote? What IDE and environment do they use to work on WordPress?

There are about 200 active contributors to core WordPress development, all of them volunteers although some are paid by their employers (including Automattic) to contribute to WordPress. There is no set development environment, everyone uses what is most comfortable to them. I have noticed a a definite bias toward using Macs, though.

What influence have WordPress got on the market and how does this affect the competitor produсts (both commercial and free)?

WordPress is definitely one of the largest publishing platforms now, but there are excellent competitors including Blogger. Innovation in the market is good because it keeps us all on our toes.

Starting from 2.3.3 version the biggest part of changes were connected with admin area and look-and-feel, and not with the code optimization. Can we hope that one day the engine will become more robust?

We are constantly rewriting, refactoring, and optimizing the code in WordPress, ofter as much as 10-20% in a single release. Since 2.3.3, probably 95% of the code has been rewritten. This deliberate process of improving the code is better than a massive rewrite because us to test each change more and preserve backward compatibility.

Do you plan to stop to support PHP4 and avoid deprecated.php usage?

Yes, in 2011.

Are there any plans to make plugins approval system more tough? Some public plugins still are of poor quality.

Eventually I’d like to bring more of the review process that we have for themes to the plugin directory, but since we encourage people to host their development on the directory I think we should be open to hosting everything.

Do you reward the plugins and themes developers?

I’m sure many plugin and theme developers are highly rewarded by their work, but we don’t give out money or anything from

Will you add some more plugins out-the-box apart from Akismet and Hello Dolly?

Probably not.

What do you think on WordPress turning from a blog engine into a full featured website CMS?

This is a pretty natural transition that started with the introduction of the Pages feature and has grown from there. More than half of new WordPress installations aren’t being used as blogs at all.

If you start to write WordPress now from the scratch – what would it look like?

Starting today I would probably leave off some features that aren’t used as much anymore, like a blogroll manager, and focus more on SEO and social integration.

What do you think about such frameworks like ZendFramework, Сodeigniter, Symfony, etc.? Didn’t you think to use it for Wordpress development?

WordPress itself is a framework you can use to build highly advanced and scalable applications.

Which CMS/CMF do you like? What projects did you keep in mind while creating WordPress?

Our about page mentions and links to Textpattern, Movable Type, and Drupal as inspirations

Thank you, Matt!

Convert latin1 to utf8

db, development, mysql Comments Off on Convert latin1 to utf8

If you import unicode text into latin1 database column, the symbols would be screwed up — russian symbols become a shit like “залоговый депозит”.

To convert such quickly (as a test) you can use Lebedev’s convertor.

To convert the whole table do the following (thanks to

  1. The most important step: dump such data in a file with mysqldump
    mysqldump -u user -p --default-character-set=latin1 --skip-set-charset --no-create-info --extended-insert --complete-insert dbname table > dbname.sql

    If not the whole table data is bad, create another table (CREATE TABLE t2 LIKE t1) and copy wrong rows to the new table.

  2. Replace latin1 by utf8 in the file
    This can be done manually in your editor or by this command:

    sed -r 's/latin1/utf8/g' dbname.sql > dbname_utf.sql
  3. Convert your latin1-table to utf8 (and maybe truncate it):
  4. Import the utf8 data back to the table:
    mysql -u user -p --default-character-set=utf8 dbname < dbname_utf.sql

That’s it.

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