Archive for the ‘Web Development’ Category

Process forking in PHP on Linux

Tuesday, August 3rd, 2010

Command Line with PHP

_ Introduced with PHP 4.3 (2002-12-27)
_ PHP packed with very useful functions: exec, shell_exec, passthru
_ PEAR package Console_CommandLine to easily handle arguments and options
_ You can do system administration and release management with a language you already know
_ Bad: if you run very long and complex processes (i.e. Parsing XML files into database), you can experience memory leaks
_ Bad: PHP is mainly for running short scripts to serve web pages so core developers focus time on that
_ Those issues are going to be addressed soon (something already done as of 5.3)

MultiProcess programming with PHP
_ ps auxf to see the parent/child process tree
_ There are basically 2 methods:
__ pcntl_fork()
__ exec

  • http://www.electrictoolbox.com/article/php/process-forking/
  • http://www.rooftopsolutions.nl/article/213
  • http://dev.mysql.com/doc/refman/5.1/en/gone-away.html (search for fork)
  • See the PHP ProcessControl class

How to benchmark apache+php

Tuesday, August 3rd, 2010

This is to see whether you server is CPU-bound or RAM-bound.

We have to stress it and see which one of those components gets saturated first.

If that is the RAM, we can add easily more RAM. The amount of RAM to add depends of the share of the CPU that can still be used before the website becomes slow.

ab -n 300 -c 1 http://www.mywebsite.com

This are the command to run during the stress test

_ uptime

_ free

_ ps -ylC httpd –sort:rss > number_of_apache_processes.txt

_ netstat -nt | grep :80 | wc -l

And obviously check how quick the website is.

How to make a transparent background/selection on an image using GIMP

Tuesday, August 3rd, 2010

http://geekswithblogs.net/TimH/archive/2006/03/20/72797.aspx

PHP Conference - London 2010 - Summary

Tuesday, August 3rd, 2010

Free notes from the PHP London Conference 2010  - http://www.phpconference.co.uk

Lost art of Simplicity by Josh Holmes (working in Microsoft)   -  http://www.slideshare.net/joshholmes/the-lost-art-of-simplicity - http://www.joshholmes.com/blog/2009/04/29/TheLostArtOfSimplicity.aspx
_ NIH (not invented here) syndrome   -  people want to develop everything internally
_ The focus shouldn’t be creating something from ground-up but putting together technologies in a way even their inventors didn’t think of
_ Simplicity is not a goal. It is the by-product of a good idea and modest expectation.
_ If it is right, you can explain it to non-technical people. Otherwise it means you haven’t understood it very well.
_ Don’t let the future complicate your present. Maybe that future you are envisaging is not going to happen
_ Get your users in the room. Be with you user while building a system to see what *they* need and expect

_ Within enterprises where are 2 complexity issues (the real one is not scalability): politics and religion (about OS, platform, …). Do *not* do technical choices based on those factors.
_ If you find yourself talking more than walking, shut up, cut the vision in half and launch the product. You can always fill in the gaps later. (Jason Fried)
_ You must understand your users and problems to avoid wasting time on unused features
_ Reuse is not always what you need. Sometimes a specific tool to solve a specific problem is better


AntiPHPPatterns
by Stefan Priebsch (PHP consultant)

_ List of common antipatterns:
__ gold hammer: try to use the same tool for too many things
__ copy&paste development
__ feature creep (proliferation of features)
__ software bloat (a lot of useless features, just because you have resources available)
__ spaghetti code
__ magic values
__ blind faith (= no checks on return values of methods)

__ proliferation of global constants

____ bad because you need to remember them, then you will probably end up replicating them
____ bad because they introduce dependencies
____ remedy: try to use class constants and, even better, provide setters (not getters) for attributes of a class instead of having the class depend on a constant.
class Something
{
protected $basePath = BASEPATH;

public function setBasePath($path)
{

}
}

instead of:

class Something
{
protected $basePath;

public function setBasePath($path)
{

}
}

Basically, remove the constant from the class, and require the caller to supply a sensible value for the base path.

__ God classes - they are classes that know too much. To promote re-usability you need to create dumb classes that don’t know anything about the application (i.e.: String Matcher)
Nowadays, PHP applications rely too much on Singletons because they are very convenient.
Singleton is bad because is like a glorified global variable (it is accessible from anywhere).
Singleton is very bad because creates dependencies and, even worse, you can’t find out those dependencies from the API. That makes testing very difficult.
The cure is the use of dependencies injection.
ORM is not always a good solution because, for example, creates a lot of queries.
The more coupled is your code, the more difficult will be to do testing.
PHP 5.3 in practice by Fabien Potencier

_ Sensio employ 70 people

_ Why 5.3? New features, much faster, uses less memory
_ What’s new in 5.3?
__ Namespaces
____ allow better interoperability and you can share the same autoloader with different projects.
____ actually the fully qualified class names are longer but you can use shortcuts using the keywords ‘use’ and ‘as’
__ Late static binding - for static classes
____ via the function get_called_class
____ it allows you to extend a singleton class (that wasn’t possible prior to PHP 5.3)
____ Anyway Singleton is not good because you can’t mock it for testing because it is hardcoded. Symfony 2.0 hasn’t got any singleton.
__ __callStatic  (like __call but for static methods)

__ anonymous functions

____ you can store a function in a variable $hello, and then call it like this: $hello() or call_user_func($hello)
____ useful with the array_* functions or anywhere you need to pass a callback function
____ a closure is an anonymous function that remembers the context when it was created
Dependencies injection is not easy in the day-to-day development because it is not very convenient.
The solution is to build a Dependency Injection Container. That is possible using closure.
Resources:
_ http://components.symfony-project.org/dependency-injection/documentation
_ pimple project on github - a simple 40-line dependency injection container
Hidden features in PHP by Johannes Schluter (release manager for PHP 5.3)
_ SPL (standard PHP Library) with data structures, exception classes, iterators - http://uk3.php.net/manual/en/book.spl.php
_ SPL iterators
__ to work on a collection of items (similar to an array)
__ you can chain iterators
__ you can use FilterIterator to remove elements from the collection
perform MySQL queries asynchronously
__ use $link->query(“SELECT ‘test’”, MYSQLI_ASYNC);  together with mysqli_poll
_ streams
__ stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream
__ very useful with file_get_contents: http://fabien.potencier.org/article/20/tweeting-from-php
__ new classes for date&time manipulation: http://php.net/manual/en/book.datetime.php
_ php -a   -  to get an interactive shell
_ inclued()  -   Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.
_ APC can be used to get the status of an upload
_ How to implement method overloading in PHP?
__ using the __call method with func_get_args
__ creating different methods with similar names
‘In search of…’ - integrating site search systems

by Ian Barber (PHP consultant for Ibuildings)

_ You can develop a search engine for your website using Google but:
___ Google can’t see your intranet
___ the Google crawler will not index new content immediately
___ maybe you want more control over the indexing

_ Technologies for implementing a search:
_ MySQL fulltext (not so good but easy)
_ Swish-e
_ Lucene (as it is written in PHP you can have problem with memory with very big datasets)
_ Xapian
_ Sphinx
_ Solr
___ High-scale: Nutch
___ High-scale: Hadoop

PHP on the D-BUS

by Derick Rethans

_ D-BUS is part of the Freedesktop.org
_ D-BUS to talk with desktop apps
_ derick at php.net

PHP - Plurilize

Tuesday, August 3rd, 2010

This is a very good post:

http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/

We have test it in the office and it works great!

PHP function to get the most recurrent words in a file - it uses Linux command line

Tuesday, August 3rd, 2010

/**
* Extracts the most recurrent one-word and two-word terms in a file
* Filters out some common stop words and you can also pass extra ones
*
* @param string $filepath
* @param int $minWordLength - the minimal word length for the terms to extract
* @param int $numberOfTerms - the number of terms to retrieve
* @return array of string - the most recurrent terms
*/
function getMostRecurrentTermsInFile ($filepath, $minWordLength, $numberOfTerms, array $extraStopWords)
{
$stopwords = array(’a', ‘about’, ‘above’, ‘above’, ‘across’, ‘after’, ‘afterwards’, ‘again’, ‘against’, ‘all’,
‘almost’, ‘alone’, ‘along’, ‘already’, ‘also’,'although’,'always’,'am’,'among’, ‘amongst’, ‘amoungst’, ‘amount’,
‘an’, ‘and’, ‘another’, ‘any’,'anyhow’,'anyone’,'anything’,'anyway’, ‘anywhere’, ‘are’, ‘around’, ‘as’, ‘at’,
‘back’,'be’,'became’, ‘because’,'become’,'becomes’, ‘becoming’, ‘been’, ‘before’, ‘beforehand’, ‘behind’, ‘being’,
‘below’, ‘beside’, ‘besides’, ‘between’, ‘beyond’, ‘bill’, ‘both’, ‘bottom’,'but’, ‘by’, ‘call’, ‘can’, ‘cannot’,
‘cant’, ‘co’, ‘con’, ‘could’, ‘couldnt’, ‘cry’, ‘de’, ‘describe’, ‘detail’, ‘do’, ‘done’, ‘down’, ‘due’, ‘during’,
‘each’, ‘eg’, ‘eight’, ‘either’, ‘eleven’,'else’, ‘elsewhere’, ‘empty’, ‘enough’, ‘etc’, ‘even’, ‘ever’, ‘every’,
‘everyone’, ‘everything’, ‘everywhere’, ‘except’, ‘few’, ‘fifteen’, ‘fify’, ‘fill’, ‘find’, ‘fire’, ‘first’, ‘five’,
‘for’, ‘former’, ‘formerly’, ‘forty’, ‘found’, ‘four’, ‘from’, ‘front’, ‘full’, ‘further’, ‘get’, ‘give’, ‘go’, ‘had’,
‘has’, ‘hasnt’, ‘have’, ‘he’, ‘hence’, ‘her’, ‘here’, ‘hereafter’, ‘hereby’, ‘herein’, ‘hereupon’, ‘hers’, ‘herself’,
‘him’, ‘himself’, ‘his’, ‘how’, ‘however’, ‘hundred’, ‘ie’, ‘if’, ‘in’, ‘inc’, ‘indeed’, ‘interest’, ‘into’, ‘is’, ‘it’,
‘its’, ‘itself’, ‘keep’, ‘last’, ‘latter’, ‘latterly’, ‘least’, ‘less’, ‘ltd’, ‘made’, ‘many’, ‘may’, ‘me’, ‘meanwhile’,
‘might’, ‘mill’, ‘mine’, ‘more’, ‘moreover’, ‘most’, ‘mostly’, ‘move’, ‘much’, ‘must’, ‘my’, ‘myself’, ‘name’, ‘namely’,
‘neither’, ‘never’, ‘nevertheless’, ‘next’, ‘nine’, ‘no’, ‘nobody’, ‘none’, ‘noone’, ‘nor’, ‘not’, ‘nothing’, ‘now’,
‘nowhere’, ‘of’, ‘off’, ‘often’, ‘on’, ‘once’, ‘one’, ‘only’, ‘onto’, ‘or’, ‘other’, ‘others’, ‘otherwise’, ‘our’, ‘ours’,
‘ourselves’, ‘out’, ‘over’, ‘own’,'part’, ‘per’, ‘perhaps’, ‘please’, ‘put’, ‘rather’, ‘re’, ’same’, ’see’, ’seem’, ’seemed’,
’seeming’, ’seems’, ’serious’, ’several’, ’she’, ’should’, ’show’, ’side’, ’since’, ’sincere’, ’six’, ’sixty’, ’so’, ’some’,
’somehow’, ’someone’, ’something’, ’sometime’, ’sometimes’, ’somewhere’, ’still’, ’such’, ’system’, ‘take’, ‘ten’, ‘than’,
‘that’, ‘the’, ‘their’, ‘them’, ‘themselves’, ‘then’, ‘thence’, ‘there’, ‘thereafter’, ‘thereby’, ‘therefore’, ‘therein’,
‘thereupon’, ‘these’, ‘they’, ‘thickv’, ‘thin’, ‘third’, ‘this’, ‘those’, ‘though’, ‘three’, ‘through’, ‘throughout’, ‘thru’,
‘thus’, ‘to’, ‘together’, ‘too’, ‘top’, ‘toward’, ‘towards’, ‘twelve’, ‘twenty’, ‘two’, ‘un’, ‘under’, ‘until’, ‘up’, ‘upon’,
‘us’, ‘very’, ‘via’, ‘was’, ‘we’, ‘well’, ‘were’, ‘what’, ‘whatever’, ‘when’, ‘whence’, ‘whenever’, ‘where’, ‘whereafter’,
‘whereas’, ‘whereby’, ‘wherein’, ‘whereupon’, ‘wherever’, ‘whether’, ‘which’, ‘while’, ‘whither’, ‘who’, ‘whoever’, ‘whole’,
‘whom’, ‘whose’, ‘why’, ‘will’, ‘with’, ‘within’, ‘without’, ‘would’, ‘yet’, ‘you’, ‘your’, ‘yours’, ‘yourself’, ‘yourselves’,
‘the’);

$stopwords = array_merge($stopwords, $extraStopWords);

// placing each word on a separate line
$command = ’sed -e “s/[^a-zA-Z]/\n/g” ‘ . $filepath;
$command .= ‘|’;
// striping out the empty lines
$command .= ‘grep -v “^$”‘;
$command .= ‘|’;
// adding lines combining all adjacent two words
// N.B.: I am commenting the single quotes inside the command
$command .= ‘awk \’(PREV!=”") {printf “%s\n%s %s\n”, PREV, PREV, $1} {PREV=$1}\”;

$command .= ‘|’;
// stripping out common stopwords (the actual command is something like this: grep -Ev ‘(\bis\b|\bsuch\b)’)
$command .= ‘grep -Evi “(\b’;
$command .= implode(’\b|\b’, $stopwords);
$command .= ‘\b)”‘;

$command .= ‘|’;
// removing all the words shorter than $minWordLength characters
$limit = $minWordLength -1;
$command .= “grep -Ev ‘^[a-zA-Z]{1,$limit}$’”;
$command .= ‘|’;
// N.B.: we are commenting the single quotes inside the command
$command .= ’sort | uniq -c | sort -nr’;
$command .= ‘|’;
// stripping out the numbers we use for sorting
$command .= “sed -e ’s/^[^0-9]*[0-9]* //g’”;

$command .= ‘|’;
$command .= ” head -n $numberOfTerms”;

$commandOutput = shell_exec($command);

$commandOutputLines = explode(”\n”, $commandOutput);

// sanitising the return
$ret = array();
foreach ($commandOutputLines as $commandOutputLine)
{
$commandOutputLine = trim($commandOutputLine);
if ( strlen($commandOutputLine) > 0 )
{
$ret[] = $commandOutputLine;
}
}

return $ret;
}

PHP - Nice Debug Trace

Friday, November 20th, 2009

<?php
echo parse_backtrace(debug_backtrace());

function parse_backtrace($raw){

$output=“”;

foreach($raw as $entry){
$output.=“\nFile: “.$entry[‘file’].” (Line: “.$entry[‘line’].“)\n”;
$output.=“Function: “.$entry[‘function’].“\n”;
$output.=“Args: “.implode(“, “, $entry[‘args’]).“\n”;
}

return $output;
}
?>

CSS Sprite Online Generator

Saturday, November 7th, 2009

http://spritegen.website-performance.org/

You can’t include animated gifs in the sprite (otherwise they will be still).

You can’t include list bullets because if the list item is quiet long, the images under the bullet point icon in the sprite will be shown.

Installing Memcached and PHP Memcache on CentOS and Ubuntu

Wednesday, November 4th, 2009

On CentOS:

Install Memcached
_ yum install memcached
_ /sbin/chkconfig memcached on
_ /etc/init.d/memcached start
_ vim /etc/sysconfig/memcached, and edit:
OPTIONS=”-l 127.0.0.1″

Install PHP extension for Memcache:
_ yum install zlib-devel
This will prevent this error from occurring:
configure: error: memcache support requires ZLIB. Use –with-zlib-dir=<DIR> to specify prefix where ZLIB include and library are located
_ pear install pecl/memcache
You should have:
/usr/lib/php/modules/memcache.so
_ echo “extension=memcache.so” > /etc/php.d/memcache.ini
_ /etc/init.d/httpd restart

On Ubuntu:

I’ve installed: apt-get install php5-memcache
I also have memcached installed: apt-get install memcached
restart apache
start memcached

Minify CSS and Javascript Files With YUI Compressor From Linux Command Line

Monday, November 2nd, 2009

You can download YUICompressor from here:

http://yuilibrary.com/downloads/#yuicompressor

Extract the package

You need Java to execute it (on Ubuntu):

sudo apt-get install sun-java6-jre

To use it, you can execute this on the command line:

cat jquery-*.min.js library.js common.js lists.js tasks.js contexts-mgmt.js keys-mgmt.js | java -jar /home/dan/Desktop/yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar –type js -o all`date +%Y%m%d%I%M%S`.js