Are PHP Namespaces Really So Bad?

February 9, 2010 Raja R.K Leave a comment

PHP developers have been demanding namespaces for some time. As PHP applications have grown larger and more complex, namespaces have become essential to prevent code clashes.

My recent tutorials received a number of comments complaining about namespace implementation in PHP. The main issues were the syntax and the backslash character. Before I tackle those issues, let’s take a quick look back at the history of PHP.

PHP is a Mess
Languages such as C# and Java were designed and follow rigorous syntax standards. PHP has evolved. The original version was released in 1995 and, by version 3, it was a popular procedural programming language. Version 4 introduced rudimentary object orientation and version 5 provides a reasonably standard OOP model. Namespaces have now been added to version 5.3.

PHP critics will argue that the language is a mess. Function names are inconsistent (e.g. strpos, str_split, substr), object handling has been tagged on, and some of the syntax is different — if not bizarre — when compared with other languages.

However, PHP remains the most widely-used server-side development language. Its versatility is one of its primary strengths:

* Novice developers can start with simple procedural programming. They need never touch OOP techniques and can still be productive.
* Code written 10 years ago in PHP 3 still works today in PHP 5.3. A few minor tweaks may be required, but major rewrites are rarely necessary.

PHP code may not always be pretty, logical, or elegant, but development is rapid and often easier to comprehend than the alternatives.

PHP Namespace Implementation

Unlike C# and Java, PHP has to retain compatibility with non-namespaced code. That has been achieved and you can choose whether to use namespaces or not. However, if you’re using PHP 5.3 (or above), I would recommend them — even if you simply use the same name throughout the whole of your project.

The choice of namespace and use as namespace operators seems logical. Some developers may disagree, but that would have been the case no matter what they’d been named.

Finally, we come to the backslash character. Most critics complain that it’s ugly, difficult to read, and awkward to type on a Mac. However, I still consider it preferable to the double-colon that was originally proposed. Examine the following static method call:

1 // PHP 5.3 beta static method call
2 echo ::App::Lib1::MyClass::WhoAmI();
3
4 // PHP 5.3 final static method call
5 echo \App\Lib1\MyClass::WhoAmI();

The second line is quicker to type, less error-prone, easier to read, and simpler to understand. If you see a backslash outside of a string, you know namespacing must be involved.

Of course, it would be great if PHP used a ‘.’ period for public methods, static methods, and namespaces. That would make it consistent with Java, C#, JavaScript, Python and many other languages. Unfortunately, PHP’s history and backwards compatibility makes that difficult to achieve.

No language is perfect, and PHP is far from it! However, namespacing has been implemented well, especially when you consider the restrictions and problems it could have caused. I’m sure you’ll learn to love that backslash!

Related reading:


How to Split WordPress Content Into Two or More Columns

February 9, 2010 Raja R.K Leave a comment

WordPress is a great CMS, but implementing some features within your theme can require a little lateral thinking. The content for your page or post is usually output by the theme code using a single function call:

the_content(args);

But what if you need to split the content into two or more blocks? That might be necessary if your theme requires multiple columns or sections on the page. WordPress provides a get_the_content() function to return content as a PHP variable, but how do you determine where the divisions occur? There are a few solutions on the web, but most involve either:

1. Splitting the content at HTML tags such as h2 headings. Unfortunately, that requires the content author to know a little HTML and it’s not very versatile — you couldn’t allow two headings in one column.

2. Using a WordPress shortcode. That’s more flexible, but it still puts the onus on the content editor to remember and use the right code.

The WordPress “<!–more–>” tag may offer a better solution. It’s normally used to split a long article into two or more pages, but not all themes use that facility and it only works for WordPress posts by default (not pages). Using the “<!–more–>” tag offers several advantages:

  • A “more” toolbar button is available in both the visual and HTML editing pane.
  • Divisions can be placed anywhere in the content.
  • It’s easy for non-technical users to understand how the content will be split.
More Tags

More Tags

To split your content, locate your theme folder (wp-content/themes), edit or create a functions.php file and add the following function within a <?php … ?> block:

1 // split content at the more tag and return an array
2 function split_content() {
3
4 global $more;
5 $more = true;
6 $content = preg_split(‘/<span id=”more-\d+”><\/span>/i’, get_the_content(‘more’));
7 for($c = 0, $csize = count($content); $c < $csize; $c++) {
8 $content[$c] = apply_filters(‘the_content’, $content[$c]);
9 }
10 return $content;
11
12 }

You now need to locate the theme files which call the_content() within the WordPress loop. You should find it in single.php and page.php since these are used to display single posts and pages respectively. It may also be found in index.php, archive.php and search.php, however, these normally show more than one article so be careful how multiple content blocks are handled.

Once you’ve found the relevant code, comment out the_content() and call the split_content() function. It returns the content as an array; each element contains a single content block split at the "<!--more-->" tag, e.g. $content[0], $content[1], $content[2] … etc. The HTML can then be output as required, e.g.

1 < ?php
2 // original content display
3 // the_content(‘<p>Read the rest of this page &raquo;</p>’);
4
5 // split content into array
6 $content = split_content();
7
8 // output first content sections in column1
9 echo ’<div id=”column1″>’, $content[0], ’</div>’;
10
11 // output remaining content sections in column2
12 echo ’<div id=”column2″>’, implode(array_shift($content)), ’</div>’;
13 ?>

How to easily monitor your webserver using PHP

February 9, 2010 Raja R.K Leave a comment

In a new post to the CatsWhoCode.com blog Jean-Babtiste Jung walks you through the creation of a simple monitoring script written using just PHP that can tell you if your web site is up and responsive.

In order to make sure that your website is always available to the public, you have to monitor it. In this tutorial, I’ll show you how you can easily create a monitoring script that will check your website availability and send an email or sms alert to you if it isn’t.

They have a snippet of code (about 15 lines long) with a function you can call to check a remote host’s connection and check the returned data for a certain string. This can not only ensure that your site is responsive but also that it’s not responding incorrectly. You could even use this to hit a certain monitoring page of your site to check for certain things (like database connection problems).

The last part of this tutorial will show you how to get sms alerts using Gmail. Please note that depending on your location and cellular phone provider, this part of the tutorial may not work.

1. Creating the monitoring script

The first part of this tutorial is to create the monitor script. Pick up your favorite text editor and create a file named monitor.php. The script is very simple: we only need two functions, one to test if a specific site is available, and the other to alert you by sending an email.

Paste the following in your monitor.php file:

01.function check($host, $find) {
02.$fp = fsockopen($host, 80, $errno, $errstr, 10);
03.if (!$fp) {
04.echo "$errstr ($errno)\n";
05.} else {
06.$header = "GET / HTTP/1.1\r\n";
07.$header .= "Host: $host\r\n";
08.$header .= "Connection: close\r\n\r\n";
09.fputs($fp, $header);
10.while (!feof($fp)) {
11.$str .= fgets($fp, 1024);
12.}
13.fclose($fp);
14.return (strpos($str, $find) !== false);
15.}
16.}
17.
18.function alert($host) {
19.mail('youremail@gmail.com', 'Monitoring', $host.' down');
20.}
21.
22.$host = 'www.catswhoblog.com';
23.$find = 'Cats Who Code';
24.if (!check($host, $find)) alert($host);

The first function we created here, check(), takes two parameters: The first is the server you’d like to check availability (for example, www.catswhocode.com) and the second parameter is to find some text on the webpage. This second parameter is an additional security: In fact, by checking if a specific word is contained on the site homepage, we ensure that the site content hasn’t been modified, for example, after a hacking.

If the server isn’t available or if the text to find hasn’t been found, the alert() function is executed, and will send an email to the account of your choice.

Save the monitor.php file and upload it to your monitoring server.

2. Defining a cron job

At this point of the tutorial, we have a working monitoring script, but we have to type http://mymonitoringserver.com/monitor.php in a web browser to check our website, which makes our script almost useless.
The solution to that problem is to create a cron task to make the server execute monitor.php every hour. Open a SSH console to your monitor server and type the following:

0 * * * * /usr/local/bin/php -q /htdocs/www/monitor.php

If your PHP scripts do not have executable permissions, 644 or -rw-r–r– for example, then as part of the command portion of the cron line, you must specify the php interpreter and pass it the filename of the PHP script (including full path to the script from your home directory) that you want executed.

3. Setting up SMS alerts

Right now, we have a working monitoring PHP script, as well as a cron job that will execute the script every hour. If a problem happens, you’ll receive an email.
Due to the popularity of iPhones, Blackberries and other SmartPhones, a lot of people are able to receive emails everywhere they are. Though, some are still using cell phones with no email capability. In this optional step of the tutorial, let’s see how we can easily receive alerts by sms.

Doing so is quite easy. First you have to use Gmail. As it is a free service, you can create a dedicated account for your monitoring alerts. Once finished, login to your account and click on the “Settings” link located on the top right side of the browser window.
Then, select “Forwarding and POP/IMAP”:

Setting up SMS alerts

Setting up SMS alerts

As shown in the previous screenshot, the only thing you have to do is to check “Forward a copy of incomming mail” and fill the field with your phone number @ your provider service.
For example, If your phone provider is AT&T, you’ll have to type 0000000000@mobile.att.net.

Passing Data Between PHP and JavaScript Using JSON(Video)

February 9, 2010 Raja R.K Leave a comment

As Developer.com mentions in a new article, there’s a new video tutorial posted over on Internet.com about using PHP and JSON to pass around data in your applications.

Got seven minutes to learn how you can harness the power of PHP, JavaScript and JSON in a powerful AJAX-driven web application? This Internet.com Video tutorial shows you all you need to know to pass data between the client and server using JSON data format.

The video explains a bit about JSON+PHP and shows you how to send a simple message (book-related data) to the server and how to handle the response with a little help from jQuery’s Ajax functions.

CAT VIDEO

February 9, 2010 Raja R.K Leave a comment

THE BEST CAT VIDEO YOU’LL EVER SEE

more about "CAT VIDEO ", posted with vodpod

Categories: Gallery Tags:

Funny Cats

February 9, 2010 Raja R.K Leave a comment

more about "Funny Cats", posted with vodpod

Categories: Gallery Tags:

Monkey seeing Mirror

February 1, 2010 Raja R.K 4 comments

more about "Monkey seeing Mirror ", posted with vodpod

Stoutgatte…Nice one

February 1, 2010 Raja R.K Leave a comment

more about "Stoutgatte…Nice one ", posted with vodpod

Monkey playing to dog

February 1, 2010 Raja R.K Leave a comment

more about "Monkey playing to dog ", posted with vodpod

The Twin Babies

January 29, 2010 Raja R.K 2 comments

more about "The Twin Babies", posted with vodpod