Mcloide's resources library

A whole bunch of ideas, concepts, PHP development and so on.

PHP Basis series – Variable types and outputting

Posted by mcloide on July 1, 2009

So far we have discussed a bit about coding and standards, a bit more about starting with PHP and now we will discuss about PHP variable types and outputting (displaying on the screen).

Some developers say that PHP have a “hybrid” variable type or, by what they mean, PHP does not carry a true primitive type since you don’t need to specify it when declaring a variable.

In some ways that’s true, you really don’t need to specify what is the variable type when declaring a variable, but that’s most because PHP engine already detects that for you automatically and it will also make the necessary conversions (cast) when necessary.

PHP has, as primary variable types:

Scalar Types

$stringType = ’string’;
$integerType = -10, 10;
$floatType = -10.9, 10.9;
$booleanType = TRUE, FALSE, 1, 0; // in this case 1 and 0 are also interpreted as boolean

Dynamic Types (compound)

$arrayType = array();
$objectType = new DirectoryReader(’./’);

Special Types

$resourceType = fopen(’file.txt’);
$nullType = NULL;

As seen above there is no need to declare the variable type to determine that it is a string, boolean, integer, float, etc. When working with several types at same time, you can cast them to become something else or, depending on the operation, PHP will do that for you.

Here is a nice example of when PHP converts something to get the result.

$result = 9 + ‘9′ – 1;

The result above will be the sum of 9 plus the integer equivalent of 9 less 1. If we were dealing with strings, the same will happen.

$result = ‘The sum of 9 + 9 is ‘ . (9+9) . ‘!’;

In this case PHP will first sum and them convert the result to a string so it can be concatenated with the rest of the string.

There is no real mystery in declaring a variable, but there are some small rules:

  1. A variable name will never start with a number, always with a letter or underscore
  2. In order to PHP to know that it’s a variable that is dealing with, the dollar sign ($) must precede all variable names
  3. The declaration of a variable must receive some value even if it’s null. This type can be later changed to the correct one with value.

Considering this all the variable declarations above are correct, but to help to get it right, here are some true examples of incorrect variable declarations.

$1234Variable = ‘1234′;
$variable;
variable = ‘test’;

The correct format for those examples above are:

$_1234Variable = ‘1234′;
$variable = null;
$variable = test;

Keep the 3 golden rules of variable declaration in mind and every time it will be right. Whenever in doubt that the variable type is really the one being looked for, just do a cast. Here are some examples;

$variable = ‘1234′;
$integerVariable = (int) $variable;
$floatVariable = (float) $variable;

Besides variable declaration the second thing most done in a PHP script is outputting results on the screen, or printing.

For most cases the printing is done by using one of the following:

  1. echo to print any scalar value on the screen, or how the manual mention it, to echo something on the screen
  2. print to print any scalar value on the screen. It’s pretty much the same as echo, but with the difference of being a function, so you can grab a result from it (that will always be 1).
  3. print_r to print arrays mostly and some objects that support the array iterator

There are more ways to output something on a document, but for now, that’s all is necessary to be known.

To wrap up this article here is a full example with correct variable declarations and the respective output.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html>
<head>
<title>
Page Title</title>
<!– other head data such as CSS styling and JS scripts –>

</head>
<body>
<p>
<?php
$_string = ‘ This is a string ‘;
$_interger = 7; // for luck
$_boolean = TRUE; // it could also be FALSE, 1 or 0
$_array = array($_string,$_interger,$_boolean);

echo $_string . ‘<br />’; // this can be also done whithout concatenation by closing the PHP tag, placing the br tag on place and opening again if needed to continue with the PHP script – look bellow

print $_interger . ‘<br />’;

print ($_boolean . ‘<br />’);
?><pre><?php
print_r($_array);
?></pre>
</p>
</body>
</html>

The document would result:

This is a string
7
1

array(
[0] => ‘This is a string’
[1] => 7
[2] => TRUE
)

Play a bit with it and do some testing, check results. Next article the focus will be on the Array which is maybe the most important type in the whole PHP engine.

Have fun.

Posted in PHP, development | Tagged: , , , , , | 2 Comments »

PHP Basis Series – Starting with PHP

Posted by mcloide on June 30, 2009

Hi and welcome to the second article of the PHP Basis Series. The first article – PHP Basis series – coding – was about coding best practices, standards and methods. A small overview on what you need to know to be a good coder.

In this second article we are going to talk about the very beginning of PHP, how it works, how to start coding on it and a bit of history.

PHP stands for Hypertext Preprocessor and it was created based on the C, Java and Perl (used until today on extra modules) languages. With many authors, editors, contributors, etc, is hard to name one as it’s creators, therefore you can point Rasmus Ledorf (who wrote the original gateway binaries) and Andi Gutmans and Zeef Suraski (both responsible for witting the parser that formed PHP3) as the original creators of PHP3.

If we had to create a in-line structure to show how it works, it would be something like this:

The client (your browser) requests a page to the server. The server reads the page and see if there are any PHP script and it will parse that script generating the correct result that can be embed to the HTML / XML / Javascript (JS) / etc.

Off course there is much more when we are talking about the way that PHP works, and it’s history, but I will focus more on the coding techniques.

Before we create our first code and I promise that it will not be “Hello World“, you will need to have PHP installed on your development machine or in a server where you can store your PHP files to be executed.

If you are on a Windows machine you can either install PHP manually adding it to IIS server or you can install a PHP bundle that will install for you the Apache server, PHP engine and MySQL (if you desire to, otherwise you can use PHP native SQLite).

Truly I’m not the best indicated to show how to install PHP on a IIS server, but there is a very good step by step – Vista – on Bills IIS Blog: How to install PHP on IIS.

Installing the bundle, for a development machine, at this point, is the most recommended. There is a great bundle, AppServ, which is pretty easy to install and configure. It will come with all of the most usual libraries that you need and you can also choose to install some extra ones.

In other hand, if you are on a Linux machine (Ubuntu, Xubuntu – love it, Suse, etc) most likely you already have PHP, Apache and MySQL installed. Therefore you can check by using the Synaptic Package Installer, and if is not there, install it. Just make sure that you have root permissions.

Now that you have PHP installed, let’s create our first code.

Note: If you don’t have an development editor, you can use Eclipse PDT. It’s a great editor and it’s free. Very similar to the Zend Studio. If you have any other editor that you like, such as Dreamweaver, Notepad, Edit+, etc, you can use it as well.

The first thing you need to know is how make the server to understand that it will be dealing with a PHP code. For that you will be using the PHP open / close tags. There are a set of 4 open / close tags for PHP, but we will focus on only one.

PHP holds as it’s open / close tags the following:

  1. <?php ?> – Full tag
  2. <? ?> – Short tags. As one of it’s variations you will have <?= that is the same as <? echo
  3. <% - ASP tags. More as a history point, but really, not useful at all.
  4. <script language=”php”></script> – besides the first one, the only one that you can trust to work.

While coding we could be using all of the 4 sets of PHP’s open / close tags, but, for keeping a standard and full compatibility on any PHP installation, we will always use the first set. The second set have some amazing features applied to it, but on the latest versions of PHP you need to enable it on the INI configuration and, if you are dealing with embending your code on a XML file you can have some parsing errors.

As I promised before, we are not going to write a “Hello World” application and we will code 2 types of application today. A standalone and a embed one. There is no real definition as standalone or embed types, but it will be easier, for now, to identify our files as standalone or embed. The standalone is a file that is purely PHP, no other code besides PHP. The embed is a HTML, XML, or any other type of file that have PHP code inside it.

Let’s take a look on a standalone file first: standalone.php (note the .php extension, whithout it, the server can’t recongnize that there is a PHP code inside it and it would only write the code on the screen as text).

standalone.php
<?php
$string    = ‘ This is a string and the number is: ‘;
$number = 7;
echo $string;
echo $number;

If you call the file from your browser (http://localhost/standalone.php) you will see the following result:

This is a string and the number is 7

As you may noticed by now, the close tag, ?>, for the above script was omitted. When you are dealing with only PHP code on a file, you don’t need to include the closing tag, the PHP engine will do that for you and it also is a simple performance and standard recomendation from PHP.

Among other uses from the standalone file, you can call it from the command prompt / command line: php /path/to/file/standalone.php. It’s results will be displayed on the command prompt screen. At first this does not seem too useful, but when getting more advanced, you will see that you can use this with cron jobs to increase your application power.

Let’s take a look now on the embed file, embed.php. Again the extension of the file must be .php otherwise the server will not understand that there is PHP code inside the file and it will not process it.

embed.php

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html>
<head>
<title>
Page Title</title>
<!– other head data such as CSS styling and JS scripts –>

</head>
<body>
<p>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>

<?php
$string    = ‘ This is a string and the number is: ‘;
$number = 7;
echo $string;
echo $number;
?>
</p>
</body>
</html>

This is a good example of a PHP script that is embed into a XHTML file. When you call the file on your browser you will have the following result:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This is a string and the number is 7

As you have notice, in the embed file the php close tag, ?>, is on place. Without it, the PHP engine would throw an error on the screen not letting the code to be parsed and the page to be displayed.

This is our first PHP application. For now on things will be increasing and we will focus a bit more on structures and tools that you can use while programming PHP.

For now on every time that we work with a PHP file that will be displayed on a browser or used on a cron job or for any other need, we will reference it as a application because that is what truly is.

See you on the next article, have fun.

Posted in PHP, development | Tagged: , , , , , , , , , , , , , | 1 Comment »

PHP Basis series – Coding

Posted by mcloide on June 29, 2009

code-standardThis is the first article that I’m writing about learning PHP.

For a couple of months now, and even more after this article from Marco Tabini, I have noticed the need of  better coding standards and a more directed learning content for “greenhorn” programmers in PHP.

Based on this, I’m starting today with a PHP Basis Series that will try to get around all the basic need that a developer should have to program well in PHP.

This first article will cover everything you need to know about coding and it’s standards.

You can learn PHP, Javascript, Java, C#, ASP.Net, Ruby on Rails, etc, if you don’t have good programming techniques and standards, your code will be messy, unreadable, hard to understand, etc.

It’s important that you have good standards and coding techniques and to emphasize that I quote a professor of mine that once said: ” A good developer learn the best pratices, standards and coding techinques, so he can program in any language.”.

While talking in PHP we have a small list of good coding practices / standars and methods.

When declaring variables and functions, use camelCase.

It’s actually simple. The variable or function will have it’s name started with a lower case and the next word will have the first letter uppercase and this will repeat for every word after.

Constants are always UPPERCASE.

This rule is more to help you out on identifying the constants among the variables.

Variables, functions names and constants must have a meaningful name.

Consider the following function:

function funtion_1($var, $var2)
{
for($i = 0; $i < $var2; $i++)
{
$var = $i + $var2;
}
return $var;
}

Looking it like this, it’s very, very hard to understand what is the use for the function or what each variable means, but re-writing it like this:

function increaseByMany($numberSource, $counter)
{
for($index = 0; $index < $counter; $index++)
{
$numberSource = $index + $counter;
}
return $numberSource;
}

It get’s really easier to understand whtat is doing and what it will return.

Use 4 spaces instead of Tabs.

Consider that you are working remotely with other developers from all over US and the World. Each developer has it’s own preferable editor. The only problem with this is that each editor can be configured to set the number of spaces for the tabs, so a developer can have 8 spaces instead of 4, for each tab. With the objective to have the correct indentation on every editor, instead of using tabs, use 4 spaces. It will be annoying at first, but it does really pay in the long run.

Have the minimal documentation for the system even if it is on the function / class itself.

This example is better visualized on a object class. Consider the creation of a class that handles every single action that a user can do on the system and this class was created more than 6 months ago. If you don’t have any inline documentation, or any documentation at all, understanding the methods inside and some specific methods from the class can be very hard. To avoid that and to allow other developers to understand how the class works, you should at least do inline commeting.

Some systems like PHPDoc, can grab the inline comments that you have written on your class and convert it, automatically, to a very professional system documentation.

Consider working with Object Oriented Programming, scalability and modularity.

Even if you are starting, working with Object Oriented Programming is a need and doing it so in a modular and scalable way is a must. The reason to work with OOP is simple: code re-use and modularity. If is well developed, you can easily allow a developer to work on a part of the system while you work on another, or you can let a developer to use a object that you already have created on his part of the system. The most important thing is that the system get’s easier to read, easier to maintain and you win on development time since you wont need to re-invent the wheel. The scalability is something that every system should consider on it’s beginning. If your system is not scalable enought there is a good chance that at some point, it will fail because it can’t grow.

Do your analysis before witting anything.

In one of my first jobs I have worked as a system architech and it was insane hard to convice the CEO that before acting, we need a plan, or by that I mean, we need to do analysis. Every time that my team tried to create something without discussing it first, things did go wrong, so, from a personal experience, if you are the system architech, do your analysis on the issue first. It will save time and you will be albe to consider how modular and scalable it can be.

Specifically to PHP

1. Never use short tags and it’s variations
2. If the document only contains PHP code, no need to use the PHP close tag ( ?> )

These are the very few basics from coding pratices / standards. Before writting a code always consider that it can become huge, that it can have 10 milhon users at time and, most important, that another developer will be reading it.

This will help you to write better code and as an advise, get the best coding standards that are out there, make a list and set on a document so every system that you work from now on you can use those and, off course, if someone joins the boat, you can send him that document too.

Have fun.

Posted in PHP, development | Tagged: , , , , , | 4 Comments »

Single Serving Sites

Posted by mcloide on June 26, 2009

I was surfing up when I came across this: http://thenethernet.com/missions/single_serving_sites at The Nethernet.

It’s shows a bunch of single serving sites which are a pretty much sites that does only one thing. Since some times images are worth more than words, here is the top 5 list. Some usefull, like “What is my Ip“, and some not so much.

  1. http://www.whatismyip.org/
  2. http://dowebsitesneedtolookexactlythesameineverybrowser.com/
  3. http://islostarepeat.com/
  4. http://r33b.net/
  5. http://thankyouandywarhol.com/ – one of the very best

Found it nice, there are more here: http://www.alistofsites.com/ and you can always take the pre-defined path on The Nethernet.
Just a note, if come across this site: http://www.instantrimshot.com/
do not press that button

Posted in fooling around | Tagged: , , , | Leave a Comment »

PHP|Architect Code Works Free webcast

Posted by mcloide on June 25, 2009

June 26th the PHP|Architect Code Works seminar will be having a FREE webcast, the first of a series. The space is limited so, run.

Here is the link: http://www.phparch.com/conferences/webcasts

Posted in News, PHP, development | Tagged: , , , | Leave a Comment »

About:HTML5

Posted by mcloide on June 24, 2009

This is one of the best contents I have seen so far about the new powerful HTML5.

Follow the link: http://camendesign.com/code/video_for_everybody

Posted in News, development | Tagged: , | Leave a Comment »

Android + Flash = iPhone but kicked

Posted by mcloide on June 24, 2009

For the happiness of Android users and the sadness of iPhone users, Flash is now supported.

So we just got word that HTC will be the first manufacturer to bring Adobe Flash to the Android platform with the release of its new Hero / Sense device. If you needed more proof that Android is here to stay and will not sit on the sidelines in the mobile operating systems game, this is it. If you think about it, the iPhone is now the only platform with substantial weight on the market that doesn’t boast support for Flash.

More about this article in MobileCrunch

Posted in News | Tagged: , , , , | 1 Comment »

Using MySQL EXPLAIN to optimize queries

Posted by mcloide on June 24, 2009

MySQL is a powerful database and when used correctly you can easily get the most of it with little.

Using the query slow logs, query optimization, database optimization and some other techiniques is a great and reliable way to guarantee that your system can respond fast.

While developing, one great tool to use from MySQL is the EXPLAIN query. It returns, for a given query, the number of results, some other information, and the extra or missing indexes that you need.

Here is a brief demonstration of how the EXPLAIN query works:

EXPLAIN SELECT tt.TicketNumber, tt.TimeIn,
               tt.ProjectReference, tt.EstimatedShipDate,
               tt.ActualShipDate, tt.ClientID,
               tt.ServiceCodes, tt.RepetitiveID,
               tt.CurrentProcess, tt.CurrentDPPerson,
               tt.RecordVolume, tt.DPPrinted, et.COUNTRY,
               et_1.COUNTRY, do.CUSTNAME
        FROM tt, et, et AS et_1, do
        WHERE tt.SubmitTime IS NULL
          AND tt.ActualPC = et.EMPLOYID
          AND tt.AssignedPC = et_1.EMPLOYID
          AND tt.ClientID = do.CUSTNMBR;

Result:

table type possible_keys key  key_len ref  rows  Extra
et    ALL  PRIMARY       NULL NULL    NULL 74
do    ALL  PRIMARY       NULL NULL    NULL 2135
et_1  ALL  PRIMARY       NULL NULL    NULL 74
tt    ALL  AssignedPC,   NULL NULL    NULL 3872
           ClientID,
           ActualPC
      Range checked for each record (index map: 0x23)

In this case because ALL is the type for each table, MySQL will generate a combination of all rows to return in the query. In another words, this takes insane long time.

Anyway, for more optimization tips and the full manual of how

this works go to the MySQL Developer Articles.


Posted in mysql | Tagged: , , , | Leave a Comment »

Justice at least – Spammers behind bars

Posted by mcloide on June 23, 2009

Finally some spammers got their last sunshine.

Yesterday the FBI got one of the most notorious group of spammers in US. They where responsible for spending an absurd amout of money in spam to gain profit with the Chinese ‘penny’ stock market (brillhant, got to admit it – this can generate insane amout of money).

More details at: http://detroit.fbi.gov/dojpressrel/pressrel09/de062209.htm

Posted in News | Tagged: , , , | Leave a Comment »

Creating applications for Android

Posted by mcloide on June 22, 2009

Google Android is becoming more and more popular with the growth of the G1 and with the upcomming new phone release.

I was checking on some documentation to see how to develop applications to the Android and I found this site (kind of slow) that have some great documentation for beginners: http://www.brighthub.com/

Here is the list of the documentation for developing Android applications:
1. Setting the Environment: Using Eclipse and Netbeans For Developing Google Android Apps
2. How-to create an Android Application: Structure I
3. How do I Develop an Android Application? Structure II
4. How-to create User Interfaces (UI) using XML : Layouts
5. How-to create an User Interface (UI) using XML : Widgets

Check it all. It will be worth your time and reading.

Posted in development, google | Tagged: , , | Leave a Comment »