Accueil / How-To with PHP

How-To with PHP

Part of the "all you need to know to become a great Drupal developer" blog series.

Performing a quick search online, many vocal critics of PHP air it's perceived shortcomings in comparison to "real" programming languages. Yet if you cut through the noise, W3Techs estimates that more than 80% of websites whose server-side programming language is known is coded in PHP. So in other words, it pretty much runs the web. This post will introduce PHP in it's simplest form and explore it's evolution into a modern, mature programming language with established standards and reusable libraries.

To start off, what is PHP? As defined on the website, PHP is a widely-used general-purpose scripting language that is especially suited for web development and can be embedded into HTML. In other words, it's primary function is to build dynamic HTML pages. Looking at a simple example, the following code will produce a webpage that shows the current day of the week.

<html>
<head>
  <title>What day is it today?</title>
</head>
<body>
<?php echo 'Today is ' . date('l'); ?>
</body>
</html>

This simple example shows how PHP can be embedded directly into HTML pages in order to render dynamic content. By using a PHP-enabled web server and placing the file named with a ".php" suffix in its root directory, the page will be interpreted and sent to the browser when requested. Installing and configuring web servers is outside the scope of this post, however more information can be found on PHP's installation guide. If you are using php 5.4, you can use the built-in web browser for testing by naming the file "index.php" and running php -S localhost:8080 on the command line. Visiting http://localhost:8080 in your browser will displays the interpreted page.

Also shown in the example above is use of date(), which is one of PHP's hundreds of built-in functions that are the fundamental power of the language. If there is no built-in function that performs the required calculation, a developer can create her own function inside of the PHP script in order to use it elsewhere in the application. For example, let's say there is a repeated need to multiply a number by itself and add one. In our PHP script, we could do the following:

<?php
function multiply_and_add_one($number) {
  return
$number * $number + 1;
}

echo
multiply_and_add_one(2); // Prints 5
?>

Developers coming from more traditional languages will notice that there are no data type declarations for the arguments passed to the function. This is because PHP is a loosely typed language, meaning that variables (denoted by a dollar sign in PHP) don't have to be explicitly bound to a data type. In fact, they can even change on the fly based on how they are being used. For example, let's take the return value of our user-defined function and place it in a textual message.

<?php
$number
= multiply_and_add_one(2); // Number variable is an integer

// Change the variable's value to "5 is is 2 squared plus 1."
$number .= ' is 2 squared plus 1.';
echo
$number; // Number variable is now a string
?>

Although early versions of PHP-based content management systems such as Drupal exclusively used functions to create frameworks and developer APIs, using object-oriented design patterns can facilitate smaller, reusable packets of code. Despite its roots and reputation as a procedural scripting language, the more recent versions of PHP have emerged as a mature, object-oriented language that can more closely resemble Java than C. To start with a basic example, the following code defines a class that stores and returns person's name.

<?php
class Person
{
    protected
$_name;

    public function
__construct($name)
    {
       
$this->_name = $name;
    }

    public function
getName()
    {
        return
$this->_name;
    }
}

$person = new Person('Chris Pliakas');
echo
$person->getName(); // Will print "Chris Pliakas"
?>

In PHP, classes are instantiated using the "new" construct, and public methods are invoked using the "->" notation. Inside of the class, instance variables are referenced using the pseudo "$this" variable which can be tricky to internalize at first, but after creating a few classes it becomes second nature.

Because PHP is so widely used, various sub-communities and frameworks have emerged in an effort to provide a reusable layer on top of PHP so that common tasks don't have to be repeated. Historically the problem is that code is isolated to each project and cannot be reused by the community as a whole. Fortunately, the Framework Interoperability Group has defined a series of standards that facilitate code reuse across projects. The most notable standard is known as PSR-0, which defined a paradigm to automatically loads class files based on their naming conventions. It also encourages sane namespacing in order prevent prevent collisions.

In order to highlight this innovation, lets namespace the "Person" class in the previous example and place it in our project's src/MyLibrary/People/Person.php file.

<?php
namespace MyLibrary\People;

class
Person
{
    protected
$_name;

    public function
__construct($name)
    {
       
$this->_name = $name;
    }

    public function
getName()
    {
        return
$this->_name;
    }
}
?>

By using a PSR-0 compliant autoloader such as the one provided by the Symfony framework, the file containing the class can automatically be loaded just by instantiating the class like we did in the example above.

<?php
use MyLibrary\People\Person;

// @see https://github.com/symfony/ClassLoader on how to register our namespace with the autoloader.

// The class file is automatically sourced by the autoloader on instantiation.
$person = new Person('Chris Pliakas');
?>

Taking it one step further, the Composer project is able to take advantage of the FIG standards in order to provide a dependency management tool that allows developers to easily pull in and manage standards compliant libraries. As an example, let's use the Guzzle project to make a REST API call to Github that obtains information about a user.

First, create a composer.json file in your project's root directory containing the following:

{
    "require": {
        "guzzle/guzzle": "~3.0"
    }
}

Next, download Composer in the project's root directory by running curl -sS https://getcomposer.org/installer | php on the command line. After Composer is installed, run php composer.phar install to download and install Guzzle and it's dependencies.

Now, let's create an index.php file which will execute our required logic.

<?php
require_once 'vendor/autoload.php';
use
Guzzle\Http\Client;

// Code stolen from http://guzzlephp.org/
$client = new Client('https://api.github.com');
$request = $client->get('/user')->setAuth('user', 'pass');
$response = $request->send();
echo
$response->getBody();
?>

Using Composer is very similar to using gems in the Ruby community, and it has spawned a wave of cooperation and quality libraries that simplify complex tasks. Through the examples in this blog, I have highlighted PHP as both a simple scripting language that can be groked by novices as a modern application development language that uses traditional design patterns that make sense to seasoned software engineers. Therefore web developers and learn and grow with PHP, which in my opinion is why it has emerged as the dominant language for the web.

Commentaires

Posted on by Maruf Billah.

I am interested in PHP programming language. I want to learn it.
Please tell me some helpful website to learn PHP.
Email: maruf.dm2010@gmail.com
Website: www.itsegment.net

Posted on by Aimy Wilson (non vérifié).

Thank you very much for sharing this informative article.The fastest growing technology in the world of web development is PHP.

Posted on by AnnyIngram (non vérifié).

It is amazing article to learn PHP from the beginning standard. It can be much useful in web industry. Can you put an output of last code her. I will come back to know output of it.

Ajouter un commentaire

Plain text

  • Aucune balise HTML autorisée.
  • Les adresses de pages web et de courriels sont transformées en liens automatiquement.
  • Les lignes et les paragraphes vont à la ligne automatiquement.

Filtered HTML

  • Use [acphone_sales], [acphone_sales_text], [acphone_support], [acphone_international], [acphone_devcloud], [acphone_extra1] and [acphone_extra2] as placeholders for Acquia phone numbers. Add class "acquia-phones-link" to wrapper element to make number a link.
  • Pour publier des morceaux de code, entourez-les avec les balises <code>...</code>. Pour du PHP, utilisez. <?php ... ?>, ce qui va colorier le code en fonction de sa syntaxe.
  • Les adresses de pages web et de courriels sont transformées en liens automatiquement.
  • Tags HTML autorisés : <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <h4> <h5> <h2> <img>
  • Les lignes et les paragraphes vont à la ligne automatiquement.
By submitting this form, you accept the Mollom privacy policy.