UltraMega Blog
27Jul/100

Create Callbacks Using __invoke

The __invoke magic method (available as of PHP 5.3) is used to make an object callable as if it were a regular function. The combines the usefulness of objects with the simplicity of functions. One application of this feature is creating callback functions that can be passed around like objects. This is common practice in other languages like JavaScript, and can be very useful. This tutorial will show you how to create a callback function using the __invoke method.

19Jul/100

Deciphering Magic Methods in PHP

Deciphering Magic Methods in PHP | Nettuts+

PHP provides a number of ‘magic’ methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. Magic methods provide some extremely useful functionality, and this tutorial will demonstrate each method’s use.

Read full tutorial at Nettuts+

4May/102

Round Robin Tournament Scheduler

Here's a snippet I wrote for a project that I thought might come in handy for someone else. It generates a schedule for a round robin tournament. I found some other snippets to do this, but I found them overly complicated or lacking in other ways.

Here's an example of what this code does:

< ?php
$players = range(1, 8);
 
echo 'Original List: ' . PHP_EOL;
print_r($players);
echo PHP_EOL;
echo 'Round Robin Schedule: ' . PHP_EOL;
print_r(generateRRSchedule($players));
?>

Output:

Original List: 
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
)
 
Round Robin Schedule: 
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 8
                )
 
            [1] => Array
                (
                    [0] => 2
                    [1] => 7
                )
 
            [2] => Array
                (
                    [0] => 3
                    [1] => 6
                )
 
            [3] => Array
                (
                    [0] => 4
                    [1] => 5
                )
 
        )
 
(...)
 
)
9Feb/104

PHP: Recursive Functions

A recursive function is a function that calls itself. This is useful for certain applications. This short tutorial will show an example of a recursive function in action.

Let's say we have the following array of categories. Normally this might be stored in a database, but we'll use an array here for simplicity.

/* Example category hierarchy:
    Tutorials
    - PHP
    -- OOP
    -- Tips
    - JavaScript
    -- Basics
    -- Frameworks
    --- jQuery
    --- MooTools
    News
    - PHP
    - Wordpress
*/
$cats = array();
$cats[1] = array('parent' => 0, 'title' => 'Tutorials');
  $cats[2] = array('parent' => 1, 'title' => 'PHP');
    $cats[3] = array('parent' => 2, 'title' => 'OOP');
    $cats[4] = array('parent' => 2, 'title' => 'Tips');
  $cats[5] = array('parent' => 1, 'title' => 'JavaScript');
    $cats[6] = array('parent' => 5, 'title' => 'Basics');
    $cats[7] = array('parent' => 5, 'title' => 'Frameworks');
      $cats[8] = array('parent' => 7, 'title' => 'jQuery');
      $cats[9] = array('parent' => 7, 'title' => 'MooTools');
$cats[10] = array('parent' => 0, 'title' => 'News');
  $cats[11] = array('parent' => 10, 'title' => 'PHP');
  $cats[12] = array('parent' => 10, 'title' => 'Wordpress');

In this case, a good application of a recursive function would be to display a breadcrumbs display of a particular category. In the example, we use the key 'parent' to identify the category that a subcategory belongs to, or 0 for the main categories.

2Feb/106

Using a PHP Class to Store Configuration

In a comment on my post listing 5 Tips for Writing Cleaner PHP Code, some good arguments were made against using constants to store configuration variables. The main arguments is that it pollutes the global namespace, which can lead to collisions when implementing other code, and the way it handles typos. This article demonstrates some of the ways constants can fail, and shows an alternative.

So here is how to store these constants in a class to avoid these problems. This puts the constants in their own namespace and prevent mistakes later on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
// Declaring your config class constants
class Config {
    const DB_HOST     = 'localhost',
          DB_USER     = 'username',
          DB_PASS     = 'password',
          ANOTHER_VAR = true;
}
 
echo Config::DB_HOST; // outputs localhost
 
echo Config::USER; // PHP Fatal error
 
if(Config::ANOTHER_VAR) {
    // do something
}
 
?>

That's all there is to it. Now all your constants are consolidated under one namespace and any typos will result in a fatal error. You can name the class whatever you want to be unique and avoid any collisions.

Tagged as: , , 6 Comments
19Jan/108

Using SSH in PHP

This tutorial will show you how to use the SSH2 functions in PHP to execute commands over SSH. This requires the SSH2 PECL extension to be installed on your server (installation instructions). Keep in mind that as of this time, the extension is in a beta state, so stability is not guaranteed.

Sending commands is fairly straightforward. You just connect, authenticate, then execute commands. Authentication can be done using a password or public key. Executing commands is a little tricky since it returns a stream that you have to handle.

Tagged as: , Continue reading