Page 198 - Open Soource Technologies 304.indd
P. 198

Unit 11: Directories and Files



            You should follow three principles on including files:                                Notes
               1.  Only use include_once or require_once. Rule number one is to always use require_once or
                 include_once to include PEAR code. If you use require, your script will likely die because
                 of redefinition errors (or it will die sometime in the future).
               2.  Determine the correlation between classes and file names. PEAR uses the one-class-per-file
                 principle, with the intention that it should be trivial to generate the required file name
                 from the class name. Replace underscores with the directory separator character, append.
                 php, and you’re finished. Here are some examples:

                          Class Name File Name

                          PEAR PEAR.php
                          XML_Parser XML/Parser.php

                          HTML_Quickform_textarea HTML/QuickForm/textarea.php
                          Case is significant here because UNIX file systems are case-sensitive.

                          Gutmans_ch12 Page 410 Thursday, September 23, 2004 2:53 PM

                          12.6 Building Packages 411

               3.  Encapsulate includes. Each file should use includes to express clearly which class it depends
                 on from other packages.




                        Scan Directories with PHP’s Directory Iterators
             O      ne of php5’s most interesting new features is the addition of iterators, a collection

                    of readmade interfaces designed to help in navigating and processing hierarchical
                    data  structures.  These  Iterators  signficantly  reduce  the  amount  of  code  required
             to process an XML document tree or a file collection. A number of Iterators are available,
             including  the  Array  Iteratior,  CachingIterator,  Limit  Iterator,  Racursive  Iterator,  Simple
             XMLIterator and Directory Iterator.

             Processing a Single-level Directory

             Let’s begin with something simple: processing a single-level directory. Type (or copy) the
             following script (Listing A), altering the directory path to reflect your local configuration:

             Listing A
             <? php

             $it = new DirectoryIterator (“/tmp/mystuff’);

             foreach $it as $file)  {
              if (!$ it-> is Dot ())  {
                                                                                 Contd...




                                             LOVELY PROFESSIONAL UNIVERSITY                                   193
   193   194   195   196   197   198   199   200   201   202   203