I converted a Java code I found online that was really useful to PHP so anyone can use it now. It basically returns the timezone of a location given its latitude and longitude. Check out the example:
<?php
include 'TimezoneMapper.php';
$london = ['lat' => 51.504380, 'lng' => -0.127727];
echo TimezoneMapper::latLngToTimezoneString($london['lat'], $london['lng']);
//outputs: Europe/London
You can get the code here: https://github.com/webmasterar/TimezoneMapperPHP
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Sunday, 17 April 2016
Saturday, 7 June 2014
Open-sourced my work projects
One of the awesome things about my last job is that I got to open source my work. More companies should do this! Among the benefits of open-sourcing work is it presents evidence of previous work and experience for the employee and for the employer it means projects get exposure and contributions from outside.
My main project is a SOP/experiment definition management system. It was written in PHP using the CodeIgniter framework with a little Zend Framework and the data is stored in a MySQL database. I'm close to finishing the paper for the project. Check out the code in the meantime: https://github.com/mpi2/impress
For the main project I created an OWL Ontology using a combination of Protégé and the Java OWLAPI to generate ontology classes and individuals from the items in the database. For those of you who want to figure out how to use the OWLAPI to build ontologies I am sure the code will help you figure it out: https://github.com/mpi2/impress_owl
Also, I'd like to point out another project I wrote which is mappings of core XML datatypes into PHP classes (with validation checking): https://github.com/mpi2/xmldatatype.
And a reminder to a previously mentioned project, PhpObo, which is a OBO file format parser and builder written in PHP: https://github.com/mpi2/PhpObo
My main project is a SOP/experiment definition management system. It was written in PHP using the CodeIgniter framework with a little Zend Framework and the data is stored in a MySQL database. I'm close to finishing the paper for the project. Check out the code in the meantime: https://github.com/mpi2/impress
For the main project I created an OWL Ontology using a combination of Protégé and the Java OWLAPI to generate ontology classes and individuals from the items in the database. For those of you who want to figure out how to use the OWLAPI to build ontologies I am sure the code will help you figure it out: https://github.com/mpi2/impress_owl
Also, I'd like to point out another project I wrote which is mappings of core XML datatypes into PHP classes (with validation checking): https://github.com/mpi2/xmldatatype.
And a reminder to a previously mentioned project, PhpObo, which is a OBO file format parser and builder written in PHP: https://github.com/mpi2/PhpObo
Labels:
codeigniter,
Github,
OBO,
OWL,
OWLAPI,
PHP,
Protege,
xml,
xml datatypes
Friday, 18 April 2014
Permutations
The other day a friend was seeking advice about passwords and password length and such and I just told him the strength of a password is based on however many characters (n) he has available to him to the power of the length of the string (l), n^l, and that he should also use non-alphanumeric characters as well and make sure it's long enough and memorable to him. Using the formula, a 4 letter password using just digits is 10^4, or 10000 possible combinations.
That got me thinking about cracking and finding combinations of passwords if you know which characters were used and in what frequency. Basically you would need to jumble the characters up and try the different combinations but because you know which characters were used the entropy is far less, l^2 - l. This would mean a 4 letter passwords using the characters abcd would have 4^2 - 4, or 12 possible combinations.
I had to put a little thought into how I was going to code this. The first thing you do when you have to write an algorithm is figure out how you would do it in real life and I thought up the idea of swivelling characters round. So, if we have the starting characters abcd, you would lock the first character and swivel the other three round:
abcd
adbc
acdb
Then, you would shift the first character (a) off the original array and push it onto the end, lock the new first character (b), and do the swivelling of the other three again:
bcda
bacd
bdac
and so on. So when I first tried to solve this problem I did it the easy way by using the php array functions:
<?php
/**
* Produce permutations of a string using php array functions
* @author Ahmad Retha
* @license public domain
*/
$s = "abcd"; //starting letters
$a = str_split($s); //converted to char array
$l = count($a); //length of array
$i = 0; //initialize counter for loop
$r = array(); //result array holds the combinations
while ($i < $l) {
$b = array_slice($a, 1); //new array missing first element
$j = 0; //initialize counter for inter-swivel
while ($j < $l - 1) {
array_push($b, array_shift($b)); //swivel smaller array
//store result in $r
$r[] = implode('', array_merge((array)$a[0], $b));
$j++;
}
array_push($a, array_shift($a)); //swivel initial character
$i++;
}
?>
But I was not satisfied with this and set about rewriting it in a more efficient way using array index manipulation to move elements around. This code is a little longer but more efficient and runs a tad faster:
<?php
/**
* Produce permutations of a string through array manipulation
* @author Ahmad Retha
* @license public domain
*/
$s = "abcd"; //starting letters
$a = str_split($s); //converted to char array
$l = count($a); //length of array
$r = array(); //result array holds the combinations
$c = 0; //counter
$t = null; //temporarily holds first char
while ($c < $l) {
$t = $a[0]; //store first char
$n = 1; //initialize counter for inner loop
for ($i = 1; $i < $l; $i++) {
while ($n < $l) {
//temporarily store first char of inner substring
$u = $a[1];
//shift chars along in substring
for ($j = 2; $j < $l; $j++) {
$a[$j - 1] = $a[$j];
}
$a[$l - 1] = $u; //push substring temp char to end
$r[] = implode('', $a); //store the permutation
$n++;
}
//shift chars along in whole string
$a[$i - 1] = $a[$i];
}
$a[$l - 1] = $t; //push temp char to end
$c++;
}
?>
This is sample output of the 12 combinations held in $r:
acdb
adbc
abcd
bdac
bacd
bcda
cabd
cbda
cdab
dbca
dcab
dabc
That got me thinking about cracking and finding combinations of passwords if you know which characters were used and in what frequency. Basically you would need to jumble the characters up and try the different combinations but because you know which characters were used the entropy is far less, l^2 - l. This would mean a 4 letter passwords using the characters abcd would have 4^2 - 4, or 12 possible combinations.
I had to put a little thought into how I was going to code this. The first thing you do when you have to write an algorithm is figure out how you would do it in real life and I thought up the idea of swivelling characters round. So, if we have the starting characters abcd, you would lock the first character and swivel the other three round:
abcd
adbc
acdb
Then, you would shift the first character (a) off the original array and push it onto the end, lock the new first character (b), and do the swivelling of the other three again:
bcda
bacd
bdac
and so on. So when I first tried to solve this problem I did it the easy way by using the php array functions:
<?php
/**
* Produce permutations of a string using php array functions
* @author Ahmad Retha
* @license public domain
*/
$s = "abcd"; //starting letters
$a = str_split($s); //converted to char array
$l = count($a); //length of array
$i = 0; //initialize counter for loop
$r = array(); //result array holds the combinations
while ($i < $l) {
$b = array_slice($a, 1); //new array missing first element
$j = 0; //initialize counter for inter-swivel
while ($j < $l - 1) {
array_push($b, array_shift($b)); //swivel smaller array
//store result in $r
$r[] = implode('', array_merge((array)$a[0], $b));
$j++;
}
array_push($a, array_shift($a)); //swivel initial character
$i++;
}
?>
But I was not satisfied with this and set about rewriting it in a more efficient way using array index manipulation to move elements around. This code is a little longer but more efficient and runs a tad faster:
<?php
/**
* Produce permutations of a string through array manipulation
* @author Ahmad Retha
* @license public domain
*/
$s = "abcd"; //starting letters
$a = str_split($s); //converted to char array
$l = count($a); //length of array
$r = array(); //result array holds the combinations
$c = 0; //counter
$t = null; //temporarily holds first char
while ($c < $l) {
$t = $a[0]; //store first char
$n = 1; //initialize counter for inner loop
for ($i = 1; $i < $l; $i++) {
while ($n < $l) {
//temporarily store first char of inner substring
$u = $a[1];
//shift chars along in substring
for ($j = 2; $j < $l; $j++) {
$a[$j - 1] = $a[$j];
}
$a[$l - 1] = $u; //push substring temp char to end
$r[] = implode('', $a); //store the permutation
$n++;
}
//shift chars along in whole string
$a[$i - 1] = $a[$i];
}
$a[$l - 1] = $t; //push temp char to end
$c++;
}
?>
This is sample output of the 12 combinations held in $r:
acdb
adbc
abcd
bdac
bacd
bcda
cabd
cbda
cdab
dbca
dcab
dabc
Tuesday, 14 January 2014
Installing PEAR packages through Composer
Did you know that you can obtain PEAR packages via Composer? And you don't need to install or set up PEAR or configure global settings!
A work colleague was talking about difficulties setting up CPAN for Perl on a server and that got me thinking about dependency managers and repositories and the options available in the PHP world. The modern way to manage dependencies and find libraries/packages is using Composer and Packagist but the old way was through using PEAR which was a global dependency manager with a repository of useful packages. I started to wonder if it was possible to load an old-style PEAR package through the new Composer dependency manager and after some fiddling about I got it working successfully.
Not long ago the PEAR guys decided to create a new version of PEAR so there are now two PEAR repositories available: classic PEAR (http://pear.php.net) and PEAR2 (http://pear2.php.net) which is also known as Pyrus. Most of the packages are still stuck in the old PEAR repository. So let's pick a test package from each of them to install. For PEAR2 I'm going to try the package suggested in the Composer documentation, PEAR2_HTTP_Request, and for old PEAR I'm going to try Numbers_Roman.
Open up the composer.json file and edit it so it looks something like this:
{
"repositories": [
{
"type": "pear",
"url": "http://pear.php.net"
},
{
"type": "pear",
"url": "http://pear2.php.net"
}
],
"require": {
"pear-pear2/PEAR2_HTTP_Request": "*",
"pear-pear/Numbers_Roman": "*"
}
}
The two different PEAR repositories are defined in the repositories section of the composer.json file. Note the first two words (pear-pear and pear-pear2) used in the paths of the require values. This allows Composer to know which repository to look in. Details about choosing alternative channels are in the Composer documentation.
Then run php composer.phar update to install the new packages.
Now we can create a new PHP file to test the packages just installed. Here's my test code. Note that PEAR2 packages are namespaced, hence the use command:
<?php
require 'vendor/autoload.php';
use pear2\HTTP\Request,
pear2\HTTP\Request\Adapter\Curl;
$url = 'http://www.yahoo.com/';
$request = new Request($url, new Curl());
$response = $request->sendRequest();
$nr = new Numbers_Roman();
//http response code 200 or 'CC' in roman numerals means success
if ('CC' == $nr->toNumeral($response->code)) {
echo "Successfully accessed $url";
} else {
echo "An error (HTTP{$response->code}) occured while trying to access $url";
}
?>
And that's it. Composer is just awesome!
A work colleague was talking about difficulties setting up CPAN for Perl on a server and that got me thinking about dependency managers and repositories and the options available in the PHP world. The modern way to manage dependencies and find libraries/packages is using Composer and Packagist but the old way was through using PEAR which was a global dependency manager with a repository of useful packages. I started to wonder if it was possible to load an old-style PEAR package through the new Composer dependency manager and after some fiddling about I got it working successfully.
Not long ago the PEAR guys decided to create a new version of PEAR so there are now two PEAR repositories available: classic PEAR (http://pear.php.net) and PEAR2 (http://pear2.php.net) which is also known as Pyrus. Most of the packages are still stuck in the old PEAR repository. So let's pick a test package from each of them to install. For PEAR2 I'm going to try the package suggested in the Composer documentation, PEAR2_HTTP_Request, and for old PEAR I'm going to try Numbers_Roman.
Open up the composer.json file and edit it so it looks something like this:
{
"repositories": [
{
"type": "pear",
"url": "http://pear.php.net"
},
{
"type": "pear",
"url": "http://pear2.php.net"
}
],
"require": {
"pear-pear2/PEAR2_HTTP_Request": "*",
"pear-pear/Numbers_Roman": "*"
}
}
The two different PEAR repositories are defined in the repositories section of the composer.json file. Note the first two words (pear-pear and pear-pear2) used in the paths of the require values. This allows Composer to know which repository to look in. Details about choosing alternative channels are in the Composer documentation.
Then run php composer.phar update to install the new packages.
Now we can create a new PHP file to test the packages just installed. Here's my test code. Note that PEAR2 packages are namespaced, hence the use command:
<?php
require 'vendor/autoload.php';
use pear2\HTTP\Request,
pear2\HTTP\Request\Adapter\Curl;
$url = 'http://www.yahoo.com/';
$request = new Request($url, new Curl());
$response = $request->sendRequest();
$nr = new Numbers_Roman();
//http response code 200 or 'CC' in roman numerals means success
if ('CC' == $nr->toNumeral($response->code)) {
echo "Successfully accessed $url";
} else {
echo "An error (HTTP{$response->code}) occured while trying to access $url";
}
?>
And that's it. Composer is just awesome!
Saturday, 4 January 2014
Reading OBO Files in PHP using PhpObo
OBO files are specially formatted text-based human-readable files that contain ontologies, terms and descriptions, that describe a domain. At work I had a requirement to look through and double check the status of certain terms in the Mammalian Phenotype (MP) ontology. My first approach was to loop through the XML-based OWL format of the MP ontology, but I soon realised the OWL file was infrequently updated and I needed something much more current to work with. The other thing I noted was that other ontologies were not available in OWL format either, so what was really needed was a way to scan through the OBO files.
I had a little search and saw that there were solutions in Java and a Perl library but nothing in PHP, which is what my main application is written in so I decided to write my own OBO parser in PHP. Initially, it was going to be a really simple script to just loop through the OBO file but after reading the OBO format specification I realised I might as well write a proper library and set about writing PhpObo for myself and anyone else who would need it.
I have published the PhpObo library on Github under the Apache 2.0 license so feel free to use it, modify it and contribute if you wish. It is written in a flexible object oriented manner so you can swap out virtually any class from the library with your own version or extend its functionality. It is not a complete solution since it only works with one document at a time and doesn't resolve external ontology dependencies. But it does serve most people's needs and allow you to loop through any OBO file and it also allows you to generate your own OBO document using either an OOP or an Array-based (ArrayAccess) approach and serialize it out in the OBO file format.
If you wish to use PhpObo in your PHP 5.3+ project, I recommend you use a PHP PSR-0 dependency manager and autoloader like Composer to import the PhpObo project via Packagist.
I had a little search and saw that there were solutions in Java and a Perl library but nothing in PHP, which is what my main application is written in so I decided to write my own OBO parser in PHP. Initially, it was going to be a really simple script to just loop through the OBO file but after reading the OBO format specification I realised I might as well write a proper library and set about writing PhpObo for myself and anyone else who would need it.
I have published the PhpObo library on Github under the Apache 2.0 license so feel free to use it, modify it and contribute if you wish. It is written in a flexible object oriented manner so you can swap out virtually any class from the library with your own version or extend its functionality. It is not a complete solution since it only works with one document at a time and doesn't resolve external ontology dependencies. But it does serve most people's needs and allow you to loop through any OBO file and it also allows you to generate your own OBO document using either an OOP or an Array-based (ArrayAccess) approach and serialize it out in the OBO file format.
If you wish to use PhpObo in your PHP 5.3+ project, I recommend you use a PHP PSR-0 dependency manager and autoloader like Composer to import the PhpObo project via Packagist.
Tuesday, 1 October 2013
Things that annoy me about OOP in PHP
I've been doing quite a bit of "proper" OOP coding in PHP lately and made a note of common pitfalls I came across. This list is not a complete run-down of what's wrong with OOP PHP. To be honest, save for these pitfalls, proper coding of PHP is actually fun.
1. Having to import every single class you use manually
In Java you say import java.util.*; where the asterisk means everything in that module is available for use in this namespace. Easy to see what's going on and a real timesaver. While using standard PSR-0 autoloading conventions, PHP doesn't have library importing so for every class you use you have to import it or give the full classpath everytime you need to use it. You will often see PHP code with long lists of 'use' statements at the beginning of the file like so:
use mylib\app\util\LoremIpsumGenerator,
mylib\app\config\ConfigLoader,
anotherlib\tastyphp\orm\TastyORM,
randomlib\randomhouse\RealRandom;
2. SPL classes have to be referenced with a preceding backslash
Instead of the PHP engine doing a simple search to find a class, first in the namespace of the file, then in the Standard PHP Library namespace, you have to delimit an SPL class with a backslash every time you use it. Why can't I just say "new Exception()" instead of "new \Exception()"? Why do I have to use a backslash everywhere I use an SPL class? It's totally unnecessary and becomes annoying to code and irritating to debug
/**
* Yes, yes, I know I should use instanceof
* but I'm showing another SPL class being used
* @throws \Exception
* @param \Exception|mylib\app\exceptions\MyBaseException
* $exception
*/
public function captureMyExceptionThrowPHPException(\Exception $exception)
{
$rc = new \ReflectionClass($exception);
if ($rc->isSubclassOf('mylib\app\exceptions\MyBaseException')) throw new \Exception('My Exception: ' . $exception->getMessage());
else throw $exception;
}
3. Lack of object casting
Seriously, why can't I cast one type of object into another, even when the subject is a subclass of the object? I wish it was possible to do this: $e = (\Exception) new mylib\app\exceptions\MyBaseException('My exception'); That would save me a bit of typing and potential buggy code.
Java allows you to upcast an object, meaning a subclass can be easily converted into a parent class, but it is not possible to downcast a parent item into a subclass type. Ideally it should be able to do that but at least it is able to upcast. PHP can't cast anything except it's primitives and two complex types (int|string|float|bool|array|object).
4. Lack of proper documentation for SPL Classes on the PHP.net site
Common SPL Functions are well documented with community supplied code snippets for everything you can imagine so it's easy to copy and paste and you're done. PHP5 SPL Classes are poorly documented, which is a real shame because some crap and procedural code from the PHP4 days has now been re-implemented in a much cleaner, better and faster object oriented way. But you wouldn't know that because of the lack of information in the manual. More work needs to be put into this. More comments with usage examples are necessary. These are provided by the community so please contribute to the project with a comment or an example if you have anything helpful.
1. Having to import every single class you use manually
In Java you say import java.util.*; where the asterisk means everything in that module is available for use in this namespace. Easy to see what's going on and a real timesaver. While using standard PSR-0 autoloading conventions, PHP doesn't have library importing so for every class you use you have to import it or give the full classpath everytime you need to use it. You will often see PHP code with long lists of 'use' statements at the beginning of the file like so:
use mylib\app\util\LoremIpsumGenerator,
mylib\app\config\ConfigLoader,
anotherlib\tastyphp\orm\TastyORM,
randomlib\randomhouse\RealRandom;
2. SPL classes have to be referenced with a preceding backslash
Instead of the PHP engine doing a simple search to find a class, first in the namespace of the file, then in the Standard PHP Library namespace, you have to delimit an SPL class with a backslash every time you use it. Why can't I just say "new Exception()" instead of "new \Exception()"? Why do I have to use a backslash everywhere I use an SPL class? It's totally unnecessary and becomes annoying to code and irritating to debug
/**
* Yes, yes, I know I should use instanceof
* but I'm showing another SPL class being used
* @throws \Exception
* @param \Exception|mylib\app\exceptions\MyBaseException
* $exception
*/
public function captureMyExceptionThrowPHPException(\Exception $exception)
{
$rc = new \ReflectionClass($exception);
if ($rc->isSubclassOf('mylib\app\exceptions\MyBaseException')) throw new \Exception('My Exception: ' . $exception->getMessage());
else throw $exception;
}
3. Lack of object casting
Seriously, why can't I cast one type of object into another, even when the subject is a subclass of the object? I wish it was possible to do this: $e = (\Exception) new mylib\app\exceptions\MyBaseException('My exception'); That would save me a bit of typing and potential buggy code.
Java allows you to upcast an object, meaning a subclass can be easily converted into a parent class, but it is not possible to downcast a parent item into a subclass type. Ideally it should be able to do that but at least it is able to upcast. PHP can't cast anything except it's primitives and two complex types (int|string|float|bool|array|object).
4. Lack of proper documentation for SPL Classes on the PHP.net site
Common SPL Functions are well documented with community supplied code snippets for everything you can imagine so it's easy to copy and paste and you're done. PHP5 SPL Classes are poorly documented, which is a real shame because some crap and procedural code from the PHP4 days has now been re-implemented in a much cleaner, better and faster object oriented way. But you wouldn't know that because of the lack of information in the manual. More work needs to be put into this. More comments with usage examples are necessary. These are provided by the community so please contribute to the project with a comment or an example if you have anything helpful.
Sunday, 8 January 2012
Submitted a new PHP class: IsPrime
I posted a new PHP class on phpclasses.org called IsPrime and it just tests to see if a number is prime or not using some simple tests/sieves before it does the usual processor-intensive test. Most solutions just quickly jump into the processor intensive method while this approach should prove a much faster way to determine if a number is prime or not.
Test 1: is the number positive - primes must be positive
Test2: is the number a single digit prime - 2,3,5,7
Test3: does the number end in 1, 3, 7 or 9 as all prime numbers do
Test4: is the number divisible by 3 or 7 - most numbers that end with 1, 3, 7 or 9 are divisible by those and are therefore not prime
Test5: is the number divisible by another prime number - if it is then it's not prime. This is the processor intensive test.
If it passes those five steps then it's prime. Here's the class: http://www.phpclasses.org/package/7281-PHP-Check-whether-a-number-is-prime.html
Test 1: is the number positive - primes must be positive
Test2: is the number a single digit prime - 2,3,5,7
Test3: does the number end in 1, 3, 7 or 9 as all prime numbers do
Test4: is the number divisible by 3 or 7 - most numbers that end with 1, 3, 7 or 9 are divisible by those and are therefore not prime
Test5: is the number divisible by another prime number - if it is then it's not prime. This is the processor intensive test.
If it passes those five steps then it's prime. Here's the class: http://www.phpclasses.org/package/7281-PHP-Check-whether-a-number-is-prime.html
Monday, 8 August 2011
Enums in PHP and Java
This is mainly for my personal reference. Enums are quite useful to use in projects and save typing and make sure Strings/Integers match, because it's not uncommon that, for example, you type "list" instead of the expected word "List" or misspell things and other such tirivial issues.
PHP:
Java:
//usage - prints out Summer
System.out.println( Season.SUMMER );
PHP:
<?php
//PHP has no native Enum type so you need to manipulate
//a normal class to work how you want it to
final class Season
{
//class constants are inherantly public and static
const SPRING = 'Spring';
const SUMMER = 'Summer';
//PHP has no native Enum type so you need to manipulate
//a normal class to work how you want it to
final class Season
{
//class constants are inherantly public and static
const SPRING = 'Spring';
const SUMMER = 'Summer';
const AUTUMN = 'Autumn';
const WINTER = 'Winter';
public function __toString()
{
public function __toString()
{
//default return
return self::SPRING;
}
}
return self::SPRING;
}
}
//Test the enum... prints out Spring.
echo ( new Season() );
echo ( new Season() );
//And if I wanted to choose just Summer
echo Season::SUMMER;
echo Season::SUMMER;
Java:
public enum Season {
//define the values
SPRING, SUMMER, AUTUMN, WINTER;
//define the values
SPRING, SUMMER, AUTUMN, WINTER;
//for extra useability have it return a string of the chosen enum when needed
@Override
public String toString(){
switch(this){
case SPRING: return "Spring";
case SUMMER: return "Summer";
case AUTUMN: return "Autumn";
case WINTER: return "Winter";
default: return "Spring";
}
}
}
@Override
public String toString(){
switch(this){
case SPRING: return "Spring";
case SUMMER: return "Summer";
case AUTUMN: return "Autumn";
case WINTER: return "Winter";
default: return "Spring";
}
}
}
//usage - prints out Summer
System.out.println( Season.SUMMER );
Friday, 2 July 2010
Nil Points
I submitted a PHP class (Music Albums Year Analyzer) to PHPClasses.org about a month ago and they nominated it for the monthly innovation award contest. Guess how many people voted for my class...
Not a single person. lol.
I came joint last (12th). Seems no-one wants to analyse their music collection or they didn't like my coding style or something?
A few months ago I submitted another class, the Bounded Queue, and I came 9th. At least that's not last. I write classes I haven't seen been done in PHP before and that are somewhat useful. But most of the cool things have already been done so what's left is not that interesting usually.
Not a single person. lol.
I came joint last (12th). Seems no-one wants to analyse their music collection or they didn't like my coding style or something?
A few months ago I submitted another class, the Bounded Queue, and I came 9th. At least that's not last. I write classes I haven't seen been done in PHP before and that are somewhat useful. But most of the cool things have already been done so what's left is not that interesting usually.
Friday, 25 June 2010
15 years of PHP
PHP was released by Rasmus Lerdorf on June 8, 1995. His original usenet post is still available online if you want to examine a computing artefact from the dawn of the web. Many of us owe our careers to the language, so here’s a brief history of PHP…
PHP originally stood for “Personal Home Page” and Rasmus started the project in 1994. PHP was written in C and was intended to replace several Perl scripts he was using on his homepage. Few people will be ancient enough to remember CGI programming in Perl, but it wasn’t much fun. You could not embed code within HTML and development was slow and clunky.
Rasmus added his own Form Interpreter and other C libraries including database connectivity engines. PHP 2.0 was born on this day 15 years ago. PHP had a modest following until the launch of version 3.0 in June 1998. The parser was completely re-written by Andi Gutmans and Zeev Suraski; they also changed the name to the recursive “PHP: Hypertext Preprocessor”.
Critics argue that PHP 3.0 was insecure, had a messy syntax, and didn’t offer standard coding conventions such as object-orientated programming. Some will quote the same arguments today. However, while PHP lacked elegance it made web development significantly easier. Programming novices could add snippets of code to their HTML pages and experts could develop full web applications using an open source technology which became widely installed by web hosts.
PHP 4.0 was released on May 22, 2000. It provided rudimentary object-orientation and addressed several security issues such as disabling register_globals. Scripts broke, but it was relatively easy to adapt applications for the new platform. PHP 4.0 was an instant success and you’ll still find it offered by web hosts today. Popular systems such as WordPress and Drupal still run on PHP 4.0 even though platform development has ceased.
Finally, we come to PHP 5.0 which was released on July 13, 2004. The language featured more robust object-orientated programming plus security and performance enhancements. The uptake has been more sedate owing to the success of PHP 4.0 and the introduction of competing frameworks such as ASP.NET, Ruby and Python.
PHP has its inconsistencies and syntactical messiness, but it’s rare you’ll encounter a language which can be installed on almost any OS, is provided by the majority of web hosts, and offers a similar level of productivity and community assistance. Whatever your opinion of the language, PHP has provided a solid foundation for server-side programming and web application development for the past 15 years. Long may it continue.
http://www.sitepoint.com/blogs/2010/06/09/php-15-birthday/
PHP originally stood for “Personal Home Page” and Rasmus started the project in 1994. PHP was written in C and was intended to replace several Perl scripts he was using on his homepage. Few people will be ancient enough to remember CGI programming in Perl, but it wasn’t much fun. You could not embed code within HTML and development was slow and clunky.
Rasmus added his own Form Interpreter and other C libraries including database connectivity engines. PHP 2.0 was born on this day 15 years ago. PHP had a modest following until the launch of version 3.0 in June 1998. The parser was completely re-written by Andi Gutmans and Zeev Suraski; they also changed the name to the recursive “PHP: Hypertext Preprocessor”.
Critics argue that PHP 3.0 was insecure, had a messy syntax, and didn’t offer standard coding conventions such as object-orientated programming. Some will quote the same arguments today. However, while PHP lacked elegance it made web development significantly easier. Programming novices could add snippets of code to their HTML pages and experts could develop full web applications using an open source technology which became widely installed by web hosts.
PHP 4.0 was released on May 22, 2000. It provided rudimentary object-orientation and addressed several security issues such as disabling register_globals. Scripts broke, but it was relatively easy to adapt applications for the new platform. PHP 4.0 was an instant success and you’ll still find it offered by web hosts today. Popular systems such as WordPress and Drupal still run on PHP 4.0 even though platform development has ceased.
Finally, we come to PHP 5.0 which was released on July 13, 2004. The language featured more robust object-orientated programming plus security and performance enhancements. The uptake has been more sedate owing to the success of PHP 4.0 and the introduction of competing frameworks such as ASP.NET, Ruby and Python.
PHP has its inconsistencies and syntactical messiness, but it’s rare you’ll encounter a language which can be installed on almost any OS, is provided by the majority of web hosts, and offers a similar level of productivity and community assistance. Whatever your opinion of the language, PHP has provided a solid foundation for server-side programming and web application development for the past 15 years. Long may it continue.
http://www.sitepoint.com/blogs/2010/06/09/php-15-birthday/
Thursday, 4 March 2010
PHP anonymous function (closure) serialization
Serialization is the conversion of object states, arrays and simple variables into a String type to allow transmission and storage for later use or by another script. PHP provides the serialize() and unserialize() functions to deal with this but after experimenting with anonymous functions (also called closures) which I blogged about earlier, I found out that trying to serialize a closure threw an exception because anonymous functions are actually internal PHP Closure objects that have serialization disabled.
I thought - "there's a gap that needs to be filled", and set out to write my second class for phpclasses.org but after a quick google search I found this (Extending PHP 5.3 Closures with Serialization and Reflection), and I must say, I'm glad I'm not the one who wrote the code for this class. The code is complex and brilliant, check it out!
I thought - "there's a gap that needs to be filled", and set out to write my second class for phpclasses.org but after a quick google search I found this (Extending PHP 5.3 Closures with Serialization and Reflection), and I must say, I'm glad I'm not the one who wrote the code for this class. The code is complex and brilliant, check it out!
Monday, 22 February 2010
PHP now supports anonymous functions
Did you know PHP 5.3 now supports anonymous functions? Let's look at some code.
This is the old way how you used to do it:
<?php
//the array we're working with
$arr = array(1,2,3,4,5);
//declare a function for use as callback
function callback($i){
echo $i;
}
//use the callback
array_walk($arr, 'callback'); //outputs 12345
?>
Now, this is the new way:
<?php
$arr = array(1,2,3,4,5);
//use anonymous callback method
array_walk($arr, function($i){echo $i;}); //outputs 12345
?>
And here's another interesting thing you can now do with PHP:
<?php
$arr = array(5,4,3,2,1);
//create a variable which will be a reference to a new function later
$fn = null;
//$fn's function is declared within the arguments of another function
array_walk($arr, $fn = function($i){echo $i;}); //outputs 54321
//calls the new function in $fn
$fn(68); //outputs 68
?>
Did you know you could use external variables inside of closures? You need the use keyword and pass the variables into it separated by commas like so:
$basePath = "/usr/home/";
$getPathFor = function($name) use ($basePath) {return "$basePath$name";}
echo $getPathFor("bob"); // /usr/home/bob
Nice.
This is the old way how you used to do it:
<?php
//the array we're working with
$arr = array(1,2,3,4,5);
//declare a function for use as callback
function callback($i){
echo $i;
}
//use the callback
array_walk($arr, 'callback'); //outputs 12345
?>
Now, this is the new way:
<?php
$arr = array(1,2,3,4,5);
//use anonymous callback method
array_walk($arr, function($i){echo $i;}); //outputs 12345
?>
And here's another interesting thing you can now do with PHP:
<?php
$arr = array(5,4,3,2,1);
//create a variable which will be a reference to a new function later
$fn = null;
//$fn's function is declared within the arguments of another function
array_walk($arr, $fn = function($i){echo $i;}); //outputs 54321
//calls the new function in $fn
$fn(68); //outputs 68
?>
Did you know you could use external variables inside of closures? You need the use keyword and pass the variables into it separated by commas like so:
$basePath = "/usr/home/";
$getPathFor = function($name) use ($basePath) {return "$basePath$name";}
echo $getPathFor("bob"); // /usr/home/bob
Nice.
Wednesday, 27 January 2010
PHP programmers are not idiots (and PHP rocks!)
PHP is currently the de facto web programming language of the internet that, from very humble beginnings, has risen to the height and eminence of being considered the worlds most popular and beloved web programming language.
The beauty of PHP lies in its simplicity and its power - it is a very simple language for beginners and is easier to learn than similar scripting languages such as Perl, but is just as, if not more powerful, than Perl and it comes with a broad array of inbuilt library functions, modules and extensions. There are an unlimited number of resources and avenues for help and support for PHP on the web and the manual is a joy to read, with the comments featuring on their pages being a goldmine of inspiration.
But what is its strength is seen as its greatest weakness in some people's eyes. Since it is so easy to learn, employers and nerds believe any fool can learn it and thus are unable to differentiate the goof from the gifted. But why does it have to be this way? Why should a developer need to put himself at a disadvantage by learning a difficult-to-learn-and-use programming language or a language limited to a single platform?
If languages were likened to paints and oils and PHP was likened to water color paint, would you call a John Constable water color a piece of crap and compare it to a five year-old's water color attempt? You wouldn't, but so many people do this because they think that if a novice can make something using it then it must be a poor medium but that view is just ignorant.
Do people wonder why PHP is so easy to learn? Have you ever spent time comparing the Java and PHP manuals? Reading the Java manual is like trying to find a flashlight in your garage in the middle of the night - it'll take you ages to find it (if you ever find it) and then you discover the batteries have run out and then you have to try out old batteries. The PHP manual, in stark contrast, is like knowing the location of the flashlight and finding it in daylight, and finding it with working batteries and a guide book next to it. Yes that's a poor analogy, but that's how it is, truly! Will someone please save us poor Java programmers and make a PHP-style Java Manual?!
The next problem is the language and platform war. Us Java and PHP programmers are platform agnostic (although we 'slightly' lean towards Unix/Linux) and we work well on almost any system, but the odd one out is Mr (I'm so high and mighty) .NET who only runs on Windows and is closed-source. But yet, the most popular language in the business sector is .NET using VB.NET and C# especially. I've nothing against C# as a language but why o' why do employers feel the need to limit their applications to a single, non-free, non-transferable platform? Why use a language that locks you in to a set of tools and a single platform? I don't get it.
Then there's the issue of the complexity of the languages themselves. PHP can be likened to Perl in its syntax and thus requires few lines to get things done and quickly, but PHP has more library methods, is easier and less cryptic to write, may use fewer lines and has good OOP features. PHP is like Perl's younger, more intelligent and more attractive sister. If you're currently banging away at Perl, you should turn over to PHP; Bioinformaticians, PHP is better and more poweful than Perl, please switch over!
And what about getting things done quickly and easily? Everyone who has tried to program Java knows it's not child's play but they can write decent programs although it takes a little longer and there are far more lines of code, but have you ever tried to do Java Enterprise Edition lately? Jesus! Hello World became Hello Universe! Not only are there very few tutorials, books and resources, but the concepts used to build the applications are numerous, difficult to grasp initially and are badly explained in introductory texts. The hardest part of learning a language is the beginning but Java EE 'takes the mick'. Do they want anyone to learn to build Java web apps? There's a reason why there is no "Idiot's guide to Java EE" book, and that's because you need to be a genius to figure it out.
From every which way you look at it, PHP seems to be the best choice as far as easy learning, fast development, less coding, more tools, more resources, platform independent, open-source solutions and more support goes. It's really a no-brainer why PHP is so popular, but it is unfair to discriminate against a developer for choosing it as their main language and loving it for all those reasons. PHP, as a tool, can be used very badly to write atrocious code but it can be used masterfully to produce a masterpiece. People sometimes forget that huge and corporate sites like Yahoo! run using PHP, that Wikipedia and almost all the major blog platforms run on it - it's not a simple toy and its developers aren't idiots, so we'd appreciate it if you didn't discriminate against us! [And give us jobs and paid us more ;) ]
By Ahmad Retha
The beauty of PHP lies in its simplicity and its power - it is a very simple language for beginners and is easier to learn than similar scripting languages such as Perl, but is just as, if not more powerful, than Perl and it comes with a broad array of inbuilt library functions, modules and extensions. There are an unlimited number of resources and avenues for help and support for PHP on the web and the manual is a joy to read, with the comments featuring on their pages being a goldmine of inspiration.
But what is its strength is seen as its greatest weakness in some people's eyes. Since it is so easy to learn, employers and nerds believe any fool can learn it and thus are unable to differentiate the goof from the gifted. But why does it have to be this way? Why should a developer need to put himself at a disadvantage by learning a difficult-to-learn-and-use programming language or a language limited to a single platform?
If languages were likened to paints and oils and PHP was likened to water color paint, would you call a John Constable water color a piece of crap and compare it to a five year-old's water color attempt? You wouldn't, but so many people do this because they think that if a novice can make something using it then it must be a poor medium but that view is just ignorant.
Do people wonder why PHP is so easy to learn? Have you ever spent time comparing the Java and PHP manuals? Reading the Java manual is like trying to find a flashlight in your garage in the middle of the night - it'll take you ages to find it (if you ever find it) and then you discover the batteries have run out and then you have to try out old batteries. The PHP manual, in stark contrast, is like knowing the location of the flashlight and finding it in daylight, and finding it with working batteries and a guide book next to it. Yes that's a poor analogy, but that's how it is, truly! Will someone please save us poor Java programmers and make a PHP-style Java Manual?!
The next problem is the language and platform war. Us Java and PHP programmers are platform agnostic (although we 'slightly' lean towards Unix/Linux) and we work well on almost any system, but the odd one out is Mr (I'm so high and mighty) .NET who only runs on Windows and is closed-source. But yet, the most popular language in the business sector is .NET using VB.NET and C# especially. I've nothing against C# as a language but why o' why do employers feel the need to limit their applications to a single, non-free, non-transferable platform? Why use a language that locks you in to a set of tools and a single platform? I don't get it.
Then there's the issue of the complexity of the languages themselves. PHP can be likened to Perl in its syntax and thus requires few lines to get things done and quickly, but PHP has more library methods, is easier and less cryptic to write, may use fewer lines and has good OOP features. PHP is like Perl's younger, more intelligent and more attractive sister. If you're currently banging away at Perl, you should turn over to PHP; Bioinformaticians, PHP is better and more poweful than Perl, please switch over!
And what about getting things done quickly and easily? Everyone who has tried to program Java knows it's not child's play but they can write decent programs although it takes a little longer and there are far more lines of code, but have you ever tried to do Java Enterprise Edition lately? Jesus! Hello World became Hello Universe! Not only are there very few tutorials, books and resources, but the concepts used to build the applications are numerous, difficult to grasp initially and are badly explained in introductory texts. The hardest part of learning a language is the beginning but Java EE 'takes the mick'. Do they want anyone to learn to build Java web apps? There's a reason why there is no "Idiot's guide to Java EE" book, and that's because you need to be a genius to figure it out.
From every which way you look at it, PHP seems to be the best choice as far as easy learning, fast development, less coding, more tools, more resources, platform independent, open-source solutions and more support goes. It's really a no-brainer why PHP is so popular, but it is unfair to discriminate against a developer for choosing it as their main language and loving it for all those reasons. PHP, as a tool, can be used very badly to write atrocious code but it can be used masterfully to produce a masterpiece. People sometimes forget that huge and corporate sites like Yahoo! run using PHP, that Wikipedia and almost all the major blog platforms run on it - it's not a simple toy and its developers aren't idiots, so we'd appreciate it if you didn't discriminate against us! [And give us jobs and paid us more ;) ]
By Ahmad Retha
Thursday, 24 September 2009
Kohana PHP framework - some tips
Recently, I've been working with the Kohana PHP Framework and there are a few hurdles I've come across and gotten past - here are a few tips.
Making your own Controller
The default gateway controller with a fresh install of Kohana is 'welcome'. This means that URIs are written a bit like this:
http://localhost/kohana/welcome/index
But it's not ideal to have 'welcome' in the URI all the time. So, if you want to choose a custom name like 'site', you need to make your own controller...
<?php html::anchor('site/index', 'Home Page'); ?>
Making your own default template
Simply go to /kohana/system/views/kohana/ and copy the template.php file to /kohana/application/views/kohana/. Edit the file as you wish. But, make sure your controller has this line pointing to it: public $template = 'kohana/template';
Making your CSS and Javascript work (get found)
So you make your XHTML template file and are ready to test everything - you stick your CSS in a .css file and your Javascript into a .js file and your images into an 'images' folder and put them in the root (/kohana/). You go to the page through the URI, e.g. http://localhost/kohana/site/index
Huh? What's this? Your CSS, Javascript and image files were not found!
Turns out you need to change the location of your files and add some PHP to your template.
html::script(array('media/js/js'), FALSE); ?>
Now this will put the typical XHTML tags into your page to include outside css and js files:
Making your own Controller
The default gateway controller with a fresh install of Kohana is 'welcome'. This means that URIs are written a bit like this:
http://localhost/kohana/welcome/index
But it's not ideal to have 'welcome' in the URI all the time. So, if you want to choose a custom name like 'site', you need to make your own controller...
- Copy the welcome controller (welcome.php) in /kohana/applications/controllers/ and paste into the same folder.
- Rename the file to site.php
- Open the site.php file and change the class declaration to 'class Site_Controller extends Template_Controller'
- Now, go to /kohana/system/config/ and copy the file called routes.php to /kohana/application/config/ .
- Open up the file and edit like so: $config['_default'] = 'site';
<?php html::anchor('site/index', 'Home Page'); ?>
Making your own default template
Simply go to /kohana/system/views/kohana/ and copy the template.php file to /kohana/application/views/kohana/. Edit the file as you wish. But, make sure your controller has this line pointing to it: public $template = 'kohana/template';
Making your CSS and Javascript work (get found)
So you make your XHTML template file and are ready to test everything - you stick your CSS in a .css file and your Javascript into a .js file and your images into an 'images' folder and put them in the root (/kohana/). You go to the page through the URI, e.g. http://localhost/kohana/site/index
Huh? What's this? Your CSS, Javascript and image files were not found!
Turns out you need to change the location of your files and add some PHP to your template.
- make a folder in root (/kohana/) called 'media'.
- make 3 folders called images, css and js inside your media folder and move your images, css and javascript files into their respective folders
- Edit your css and js files to point to the right path for the images, e.g: background-image: url(/kohana/media/simages/bg.png); (make sure the first / is there otherwise it won't work
- Now edit your template file to include this bit of code in the head section (I called my css file and js file css.css and js.js (imaginative huh?)):
html::script(array('media/js/js'), FALSE); ?>
Now this will put the typical XHTML tags into your page to include outside css and js files:
<link rel="stylesheet" type="text/css" href="/kohana/media/css/css.css" media="screen" />
<script type="text/javascript" src="/kohana/media/js/js.js">