You might be surprised, but a right choise of the project text encoding can affect the project file size and amount of bugs.
To avoid bugs of wrong presentation of text on your page, make sure that all database entities and the application server (PHP) use the same encoding. That helps to forget about issues connected with text presentation.
On database side, make sure you set the correct encoding to:
database,
tables,
columns,
import-export tools parameters (a big source of wrong encoding bugs),
corresponding SQL server variables
On application server it’s usually just one query –
SET NAMES utf8
Pay attention, that utf8 might be not the best choise for your project: every non-English character needs 2-6 bytes of memory, so if you built a one-language (local) project with lots of database data, consider using a 1 byte encoding like windows-1251 and save about half of the space on server file system.
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.
Example:
// 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 {
const
KINGDOM = 'Animalia',
PHYLUM = 'Chordata',
FAMILY = 'Felidae';
public
$tail,
$whisker = '\/',
$head,
$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.
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:
It’s handy to use in Zend FW driven project. For example, you want to make an in-place tracker (e.g. Google Analytics) — you create a helper class My_View_Helper_Tracker inherited from Zend_View_Helper, Zend finds its automatically and then you are free to use your helper method:
echo $this->tracker( $trackerID );
The question is what you gonna do if you want a base class for a family of trackers?
It’s not so obvoius due to naming conventions.
Let’s say you want 2 kinds of trackers: Google Analytics and Euroads.
1. You create such files structure:
library
- My
- View
- Helper
- Tracker
Abstract.php
- Google
Page.php
- Euroads
Owner.php
Guest.php
If you want to work with big files uploads (photos, videos, CSV data dumps) you might need to prepare your PHP server for this — increase the values of these variables in your php.ini:
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
I want to share a couple of features I use to handle AJAX requests in projects based on Zend Framework.
1. AJAX request handling
What: some parts of your application can be not loaded if currect request is AJAX.
Why: you don’t need views, templates, some routes — so you can add an AJAX check in your Initializer or bootstrap file and avoid loading not necessary things.
How: Zend Request object has a to find out whether it’s AJAX request or not. It’s based on ‘X-Requested-With‘ header, which is sent by jQuery, Prototype, Scriptaculous, YUI and MochiKit frameworks.
2. AJAX Controller
Most AJAX controller’s methods I saw had an exit() inside to not to output Zend’s template — it is a work-around. The proper way to do so is to tell to Zend not to load anything. One step forward is to create an abstract Controller class and inherit all you AJAX classes from it:
/library/Koodix/Controller/Ajax/Action.php:
<?php
require_once 'Zend/Controller/Action.php';
abstract class Koodix_Controller_Ajax_Action
extends Zend_Controller_Action
{
public function init() {
//disable the standard layout output
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
}
public function postDispatch() {
//envelope and output json field
if( !empty( $this->json ) ) {
echo json_encode( $this->json );
}
}
}
<?php
class AjaxController extends Koodix_Controller_Ajax_Action
{
// bla-bla-bla
Take a look at postDispatch method — idea behind it is to convert to JSON and output anything that is set to json field of your controller. If you want to send JSON data in special header (and not in body, like it’s done in my example), you can do it in this method.
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:
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:
Give a small piece of big work to an agent.
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).
If work is done — go to step #1.
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:
one to remember ID of agent that is processing this record (let’s call this column ‘locked_by‘)
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.
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 .
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
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.
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:
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:
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 setting, second — by setting PHP value:
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 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 — . 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:
Several years ago I created PHP class to import CSV files to a database table very quickly ( 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.
“” is a PHP example application that imports CSV file to a database table with visual mapping of CSV columns to table columns.
Of course, you can get a copy of the application source – just go to the .
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:
Open Quick_CSV_import.class and find “LOAD DATA INFILE“
change it to “LOAD DATA LOCAL INFILE“
It’s connected with permissions at your Linux server. Thanks to for the solution.
Once upon a time I took a look at my Google Analytics account and found out that is 5th source medium for two my blogs (this one and my ).
I have . Calculation shows that 7% of my blogs visitors are my classes downloaders and viewers for all the time my classes and blogs exist, and 11% – for last week.
Take into account, that
I get these people to me without any move – I have just placed the links once.
in-bound links improve Google PageRank
count of links is limited only by your imagination ;]
To check that all my classes have all needed links in “Related links” section, I wrote a PHP script that adds a link if it’s not present on your class page. It was written fast so there not so much error checks; to use it, just
type your login/pass,
list IDs of your classes and
define the list of links to be placed in “Related links” section of every class page.
Script supports more than one login/pass pair. If such link is already present, it will be skipped. is required for your PHP server.
Another my class has become a winner of PHP Classes Innovation Award – it’s the implementation of algorithm. Yes, it’s the algorithm we all know from university – it’s strange for me, that it was considered as innovative.
I wrote this class as a test task while an interview for a new job. Results were so impressive for me, that I decided to share this piece of code: it finds result in 10Gb file for less than 5 seconds! File must contain key/value pairs (separator can be defined, by default it’s equal sign), and these pairs are sorted by keys. You define what key to search and get correspondent value very quickly.
For example:
Ann=5
Bob=3
Sandy=8
Zulu=1
If you search “Sandy”, you’ll get result “8″. Very quick :]
As a prize I selected an Apress book called “” – though I found it in PDF, it seems to be quite insightfull for me: we, developers, always think about code, and never about how to sell it. I have several product ideas, so I hope the book would help me to succeed.
P.S. Fun is that a few people emailed me to say how nice my new PHP Classes avatar is :] Thanks to Anton Dovgal for such a great picture of sad me.
Recent Comments