PHP
  Home arrow PHP arrow Page 4 - Collections and Sorting
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Collections and Sorting
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 19
    2006-03-28

    Table of Contents:
  • Collections and Sorting
  • Weighing the Options
  • Building the Foundation
  • Concrete Classes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Collections and Sorting - Concrete Classes


    (Page 4 of 4 )

    Now it is time to create an actual concrete implementation of the abstract Collection class and the ISortable interface. We will use a class called People for our collection. It will contain objects of the type Person. Really, it can contain any object implementing ISortable, but in our example we will only use the class Person. For now, the Person class is going to be just a glorified container for a single string, $name.

    class Person implements ISortable
    {
         private $name;
         public function GetName() { return $name; }
         public function SetName($name) { $this->name = $name;     }
         public function GetSortKey()
         {
              return $this->name;
         }    

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

    Next we need to implement the People collection and its Sort() method. As I mentioned earlier in the article, there are quite a lot of ways to sort. For this example I will use the "fundamental" sort algorithm - the Bubble Sort. I should also point out that it is the slowest sort and should never be used on large data sets or where performance is a critical concern.

    class People extends Collection
    {
         public function Sort()
         {
              for ($i = $this->data->count() - 1; $i >= 0; $i--)
              {
                  $flipped = false;
                  for ($j = 0; $j < $i; $j++)
                  {
                       if (strcmp($this->data[$j]->GetSortKey(), 
                            $this->data[$j + 1]->GetSortKey()) > 0)
                       { 
                            $tmp = $this->data[$j];
                            $this->data->offsetSet($j, 
                                 $this->data[$j + 1]);
                            $this->data->offsetSet($j + 1, $tmp);
                            $flipped = true;
                       }
                  }
                  if (!$flipped)
                       return;
              }
         }
    }

    The Bubble Sort is by far the most obvious and intuitive sort algorithm, performing in-place swaps in a linear fashion. Notice that it will return early if any pass does not cause a swap - which means in an example like this one, it's just fine. Even if it did not return early, we will be working with so few elements that it simply does not matter. Consider the following example:

    $people = new People();
    $people->Append(new Person('Jamie'));
    $people->Append(new Person('David'));
    $people->Append(new Person('Natalie'));
    $people->Append(new Person('Johnny'));

    print '<pre>';

    print_r($people);

    $people->Sort();

    print_r($people);

    print '</pre>';

    You should see this in your browser after running the script:

    People Object
    (
        [data:protected] => ArrayObject Object
            (
                [0] => Person Object
                    (
                        [name:private] => Jamie
                    )
                [1] => Person Object
                    (
                        [name:private] => David
                    )
                [2] => Person Object
                    (
                        [name:private] => Natalie
                    )
                [3] => Person Object
                    (
                        [name:private] => Johnny
                    )
            )
    )
    People Object
    (
        [data:protected] => ArrayObject Object
            (
                [0] => Person Object
                    (
                        [name:private] => David
                    )
                [1] => Person Object
                    (
                        [name:private] => Jamie
                    )
                [2] => Person Object
                    (
                        [name:private] => Johnny
                    )
                [3] => Person Object
                    (
                        [name:private] => Natalie
                    )
            )
    )

    Conclusion

    There it is, a minimal implementation of collections with sorting. We have defined two interfaces and an abstract collection class and created a uniform way to sort within our collection. By sacrificing the ability to use an indexer on our collection, we were able to encapsulate the sort functionality within the collection class itself, sparing ourselves the trouble of creating even more classes.

    Having now implemented the worst possible sort algorithm and left an obvious re-factoring or two, the stage is set for the next installment of this article. In the next part we are going to actually implement a number of sort algorithms and benchmark them with a much larger data set. If you need to learn the fundamental sort algorithms (and all programmers do), be sure you check it out!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Thanks for reading!
       · I can't even begin to tell you how grateful I am that you posted this. I was totally...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT