SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
________                   __________________      ______
                      ___ __ )__________ ____ ___ /___(_)__ __/___ ____ /
                      __ __ | _  __ `/ / / / __/_ /__ /_ _ / / /_ /
                      _ /_/ // __/ /_/ // /_/ // /_ _ / _ __/ / /_/ /_ /
                      /_____/ ___/__,_/ __,_/ __/ /_/ /_/     __,_/ /_/



                         ______ _     _ ______      _______ _       _      ______             _
                        (_____ (_)   (_|_____     (_______|_)     | |    / _____)           (_)       _
                         _____) )______ _____) )    _       _      | |   ( (____   ____ ____ _ ____ _| |_ ___
                        | ____/ ___ | ____/        | |     | |     | |    ____  / ___)/ ___) | _ (_    _)/___)
                        | |    | |   | | |         | |_____| |_____| |    _____) | (___| |   | | |_| || |_|___ |
                        |_|    |_|   |_|_|          ______)_______)_|   (______/ ____)_|   |_| __/ __|___/
                                                                                                |_|




                        Jesse G. Donat <donatj@gmail.com>

                                               donatstudios.com

                                              github.com/donatj

                                                          @donatj


Sunday, March 3, 13
ABOUT ME

    • Programming           Professional for 7 years.

    • First computer was a monochrome Epson
        running DOS 3.22

    • Started         programming at age 11 (QBasic)

    • Works           for Capstone Digital

    • Spent  my 21st birthday in a Japanese Police
        Department

Sunday, March 3, 13
WHAT?
                 Using PHP as a Shell Script, while making it
                     both useful and visually appealing.
                                That’s What!

                                    UNIX Like
                              Sorry, Windows Developers :(


                                 High Level Skim



Sunday, March 3, 13
WHY COMMAND LINE?
                              Why not?

                             Data Processing

                          Long Running Processes

                              Tools / Utilities

                           Component Testing



Sunday, March 3, 13
WHY PHP?
                       Why not?

                        Familiarity

                        Flexibility

                       Ease of Use

                       Code Reuse



Sunday, March 3, 13
EXAMPLES


                        Composer

                         PHPUnit

                      phpDocumentor

                          Phing



Sunday, March 3, 13
HOW?




Sunday, March 3, 13
<?php

       echo	
  "Hello	
  World!";
       echo	
  PHP_EOL;




                                    GOOD ENOUGH?




Sunday, March 3, 13
<?php

       echo	
  "Hello	
  World!";
       echo	
  PHP_EOL;




                             WE CAN DO BETTER!
       #!/usr/bin/env	
  php
       <?php

       fwrite(	
  STDOUT,	
  "Hello	
  World!"	
  );
       fwrite(	
  STDOUT,	
  PHP_EOL	
  );




Sunday, March 3, 13
#! ???
    •   Known as shebang, hash-bang, pound-bang,
        etc
    •   “Interpreter Directive”
    •   Absolute path
         •   #!/usr/bin/php
    •   #!/usr/bin/env php
         •   More portable
         •   Executes from your $PATH
    •   Script must be set executable
         •   chmod +x my_awesome_script.php

Sunday, March 3, 13
OTHER NOTES


                      When using hash-bang, must use UNIX
                                   linefeeds

                        Make sure max_execution_time not
                      overridden as included frameworks may
                                     reset this.



Sunday, March 3, 13
SYSTEM CALLS
    •   `call` - Backtick operator                      •   passthru( string $command [, int &$return_var ] )
         •   Returns result as string                       •   Sends result directly to output
         •   Easy, least flexible.                           •   Second parameter is the status code
         •   Can be difficult to spot in code.
    •   shell_exec( string $cmd )
         •   Identical to the Backtick operator
    •   exec( string $command [, array &$output [, int &$return_var ]] )
         •   Returns only the last line of the result
         •   Entire output is retrieved by reference through the second parameter
         •   Third parameter is the status code by reference


Sunday, March 3, 13
PROCESS CONTROL


    • proc_*              php.net/manual/en/function.proc-open.php

    • Good    for long running external commands where you want
        to parse the output in real time

    • Complicated      to use



Sunday, March 3, 13
define('BUF_SIZ',	
  	
  20);	
  	
  	
  	
  	
  #	
  max	
  buffer	
  size
       define('FD_WRITE',	
  0);	
  	
  	
  	
  	
  	
  #	
  STDIN
       define('FD_READ',	
  	
  1);	
  	
  	
  	
  	
  	
  #	
  STDOUT
       define('FD_ERR',	
  	
  	
  2);	
  	
  	
  	
  	
  	
  #	
  STANDARDERROR
       function	
  proc_exec($cmd)	
  {
       	
  	
  	
  	
  $descriptorspec	
  =	
  array(
       	
  	
  	
  	
  	
  	
  	
  	
  0	
  =>	
  array("pipe",	
  "r"),
       	
  	
  	
  	
  	
  	
  	
  	
  1	
  =>	
  array("pipe",	
  "w"),
       	
  	
  	
  	
  	
  	
  	
  	
  2	
  =>	
  array("pipe",	
  "w")
       	
  	
  	
  	
  );
       	
  	
  	
  	
  $ptr	
  =	
  proc_open($cmd,	
  $descriptorspec,	
  $pipes);
       	
  	
  	
  	
  if	
  (!is_resource($ptr))
       	
  	
  	
  	
  	
  	
  	
  	
  return	
  false;
       	
  	
  	
  	
  while	
  (($buffer	
  =	
  fgets($pipes[FD_READ],	
  BUF_SIZ))	
  !=	
  NULL	
  
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  ||	
  ($errbuf	
  =	
  fgets($pipes[FD_ERR],	
  BUF_SIZ))	
  !=	
  NULL)	
  {
       	
  	
  	
  	
  	
  	
  	
  	
  if	
  (!isset($flag))	
  {
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $pstatus	
  =	
  proc_get_status($ptr);
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $first_exitcode	
  =	
  $pstatus["exitcode"];
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $flag	
  =	
  true;
       	
  	
  	
  	
  	
  	
  	
  	
  }
       	
  	
  	
  	
  	
  	
  	
  	
  if	
  (strlen($buffer))	
  fwrite(STDOUT,	
  $buffer);
       	
  	
  	
  	
  	
  	
  	
  	
  if	
  (strlen($errbuf))	
  fwrite(STDERR,	
  "ERR:	
  "	
  .	
  $errbuf);
       	
  	
  	
  	
  }
       	
  	
  	
  	
  foreach	
  ($pipes	
  as	
  $pipe)	
  {	
  fclose($pipe);	
  }
       	
  	
  	
  	
  /*	
  Get	
  the	
  expected	
  *exit*	
  code	
  to	
  return	
  the	
  value	
  */
       	
  	
  	
  	
  $pstatus	
  =	
  proc_get_status($ptr);
       	
  	
  	
  	
  if	
  (!strlen($pstatus["exitcode"])	
  ||	
  $pstatus["running"])	
  {
       	
  	
  	
  	
  	
  	
  	
  	
  /*	
  we	
  can	
  trust	
  the	
  retval	
  of	
  proc_close()	
  */
       	
  	
  	
  	
  	
  	
  	
  	
  if	
  ($pstatus["running"])
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  proc_terminate($ptr);
       	
  	
  	
  	
  	
  	
  	
  	
  $ret	
  =	
  proc_close($ptr);
       	
  	
  	
  	
  }	
  else	
  {
       	
  	
  	
  	
  	
  	
  	
  	
  if	
  ((($first_exitcode	
  +	
  256)	
  %	
  256)	
  ==	
  255	
  
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  &&	
  (($pstatus["exitcode"]	
  +	
  256)	
  %	
  256)	
  !=	
  255)
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $ret	
  =	
  $pstatus["exitcode"];
       	
  	
  	
  	
  	
  	
  	
  	
  elseif	
  (!strlen($first_exitcode))
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $ret	
  =	
  $pstatus["exitcode"];
       	
  	
  	
  	
  	
  	
  	
  	
  elseif	
  ((($first_exitcode	
  +	
  256)	
  %	
  256)	
  !=	
  255)
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $ret	
  =	
  $first_exitcode;
       	
  	
  	
  	
  	
  	
  	
  	
  else
       	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  $ret	
  =	
  0;	
  /*	
  we	
  "deduce"	
  an	
  EXIT_SUCCESS	
  ;)	
  */
       	
  	
  	
  	
  	
  	
  	
  	
  proc_close($ptr);
       	
  	
  	
  	
  }
       	
  	
  	
  	
  return	
  ($ret	
  +	
  256)	
  %	
  256;
       }




Sunday, March 3, 13
TERMINAL INFORMATION
                                      tput makes a very good friend!

         Size in columns                                        tput cols

             Size in rows                                      tput lines

       Supported
                                                               tput colors
     Number of Colors

       $rows	
  =	
  intval(`tput	
  lines`);
       $cols	
  =	
  intval(`tput	
  cols`);
       echo	
  "Your	
  terminal	
  is	
  {$rows}x{$cols}!";




Sunday, March 3, 13
STREAMS




Sunday, March 3, 13
Sunday, March 3, 13
STANDARD STREAMS

           Standard Output             Standard Error               Standard Input

                      STDOUT                 STDERR                        STDIN

    The main application output to A second output stream to The main input stream into a
            the terminal.                the terminal.                program.

      Stream most easily piped for Useful for error messages as Generally directly from the
          logging or secondary      well as control codes and end users keyboard unless
               processing.          other you wouldn’t want         otherwise piped.
                                     sent to a piped output.




Sunday, March 3, 13
STANDARD OUT NOTES

                      • echo   “Hello World!”;

                        • php://output     is not necessarily standard out

                        • Susceptible    to output buffering

                      • fwrite(   STDOUT, "Hello World!" );

                        • More     explicit!


Sunday, March 3, 13
READING STANDARD IN
                      Its just like reading from a file, very slowly.

        fwrite(	
  STDERR,	
  "Are	
  you	
  sure	
  (y/n):	
  "	
  );   while(	
  $line	
  =	
  fgets(	
  STDIN	
  )	
  )	
  {
        if(	
  fread(	
  STDIN,	
  1	
  )	
  ==	
  'y'	
  )	
  {         	
  	
  fwrite(	
  STDOUT,	
  $line	
  );
        	
  	
  	
  	
  fwrite(	
  STDOUT,	
  "Super	
  Cool!"	
  );     }
        }else{
        	
  	
  	
  	
  fwrite(	
  STDOUT,	
  "LAME!"	
  );
        }

        fwrite(	
  STDOUT,	
  PHP_EOL	
  );




Sunday, March 3, 13
COMMAND LINE
                       ARGUMENTS



Sunday, March 3, 13
BASIC ARGUMENTS

    • Global          $argv          • Useful for simple single
                                      scripts accepting a small
    • First argument is always the    number of parameters
        executed script




Sunday, March 3, 13
COMPLEX ARGUMENTS
        $shortopts	
  	
  =	
  "r:";	
  	
  //	
  Required	
  value
        $shortopts	
  .=	
  "o::";	
  //	
  Optional	
  value
        $shortopts	
  .=	
  "abc";	
  //	
  These	
  options	
  do	
  not	
  accept	
  values

        $longopts	
  	
  	
  =	
  array(
        	
  	
  	
  	
  "reqval:",	
  	
  	
  	
  	
  	
  	
  //	
  Has	
  a	
  value
        	
  	
  	
  	
  "optval::",	
  	
  	
  	
  	
  	
  //	
  Optional	
  value
        	
  	
  	
  	
  "noval",	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  No	
  value
        );
        $options	
  =	
  getopt($shortopts,	
  $longopts);
        var_dump($options);




Sunday, March 3, 13
FURTHER INFORMATION
                            Other Simple Operations

              Is the code
                running       $is_cli	
  =	
  substr(php_sapi_name(),	
  0,	
  3)	
  ==	
  'cli';
              in the CLI?



              Is a stream               $is_piped	
  =	
  !posix_isatty(STDOUT);
             being piped?


Sunday, March 3, 13
CONTROL CODES
                          It’s about to get good!




Sunday, March 3, 13
• More            are prefixed with the ASCII “Escape” character: “033”

    • Let         you control terminal behaviors and format output.

         • Cursor        Control (Positioning Text)

         • Colors

         • Erasing       (Screen, Lines, Etc)

         • Raise       a “Bell”

         • More!

    • bit.ly/controlcodes                             www.termsys.demon.co.uk/vtansi.htm


Sunday, March 3, 13
CURSOR CONTROL
                            Up           033[{COUNT}A

                          Down           033[{COUNT}B

                      Forward (Right)    033[{COUNT}C

                      Backwards (Left)   033[{COUNT}D

                       Force Position    033[{ROW};{COLUMN}f

                           Save          0337

                          Restore        0338

Sunday, March 3, 13
ERASING
                        Erase Screen             033[2J

                        Current Line             033[2K

                       Current Line UP           033[1J

                      Current Line Down          033[J

                       To Start of Line          033[1K

                        To End of Line           033[K

Sunday, March 3, 13
COLORS!
    • Standard                    8-Color Set

         • Black             / Red / Green / Yellow / Blue / Magenta / Cyan / White

    • Extended                     xterm-256 Color Set

         • Not Well                     Supported
   Detection!
       #!/usr/bin/env	
  php
       <?php

       $colors	
  =	
  max(8,	
  intval(`tput	
  colors`));
       fwrite(	
  STDOUT,	
  "Terminal	
  supports	
  {$colors}	
  colors!"	
  );
       fwrite(	
  STDOUT,	
  PHP_EOL	
  );



Sunday, March 3, 13
Great for warnings (red!)

                         Great for separating ideas.

                      Hated by UNIX beards world over




Sunday, March 3, 13
STANDARD STYLING
             Attribute           Code         033[{attributes separated by semicolon}m
             Reset All            0
           Bright (Bold)          1
                                                fwrite(	
  STDOUT,	
  "033[31m"	
  	
  	
  .	
  "Red	
  Text"	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .	
  PHP_EOL	
  );
                 Dim              2             fwrite(	
  STDOUT,	
  "033[4m"	
  	
  	
  	
  .	
  "Red	
  And	
  Underlined	
  Text"	
  .	
  PHP_EOL	
  );
                                                fwrite(	
  STDOUT,	
  "033[0m"	
  	
  	
  	
  .	
  "Normal	
  Text"	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .	
  PHP_EOL	
  );
             Underline            4             fwrite(	
  STDOUT,	
  "033[31;4m"	
  .	
  "Red	
  and	
  Underlined	
  Text"	
  .	
  PHP_EOL	
  );

                Blink             5
      Reverse (Inverted)          7
              Hidden              8
                Color       Foreground Code   Background Code
                 Black            30                      40
                 Red              31                      41
                Green             32                      42
                Yellow            33                      43
                 Blue             34                      44
               Magenta            35                      45
                 Cyan             36                      46
                White             37                      47

Sunday, March 3, 13
RESET!




                      EOL AT THE END!


Sunday, March 3, 13
OTHER NOTES

    •   Best Practice: send all control codes to standard error

    •   “007” is the ASCII Bell Character

    •   PHP errors by default output to standard out, not standard error

    •   Status Codes

         •   Let the world outside your script know there was a problem

         •   die(1); //non-zero implies error

Sunday, March 3, 13
PUTTING IT TOGETHER!




Sunday, March 3, 13
for($i	
  =	
  0;	
  $i	
  <=	
  100;	
  $i	
  +=	
  5)	
  {
       	
  	
  	
  	
  fwrite(	
  STDOUT,	
  "{$i}%	
  Complete"	
  .	
  PHP_EOL	
  );
       	
  	
  	
  	
  usleep(	
  100000	
  );
       }




Sunday, March 3, 13
fwrite(	
  STDOUT,	
  "0337"	
  );	
  //	
  Save	
  Position
       for($i	
  =	
  0;	
  $i	
  <=	
  100;	
  $i	
  +=	
  5)	
  {
       	
  	
  	
  	
  fwrite(	
  STDOUT,	
  "0338"	
  .	
  "{$i}%	
  Complete"	
  );	
  //	
  Restore	
  Position	
  and	
  Write	
  Percentage
       	
  	
  	
  	
  usleep(	
  100000	
  );
       }
       fwrite(	
  STDOUT,	
  PHP_EOL	
  );




Sunday, March 3, 13
fwrite(	
  STDOUT,	
  "0337"	
  );	
  //	
  Save	
  Position
       for($i	
  =	
  0;	
  $i	
  <=	
  100;	
  $i	
  +=	
  5)	
  {
       	
  	
  	
  	
  $step	
  =	
  intval($i	
  /	
  10);
       	
  	
  	
  	
  fwrite(	
  STDERR,	
  "0338");	
  //	
  Restore	
  Position
       	
  	
  	
  	
  fwrite(	
  STDERR,	
  '['	
  .	
  str_repeat('#',	
  $step)	
  .	
  str_repeat('.',	
  10	
  -­‐	
  $step)	
  .	
  ']'	
  	
  );	
  //	
  Write	
  Progress	
  Bar
       	
  	
  	
  	
  fwrite(	
  STDOUT,	
  "	
  {$i}%	
  Complete"	
  .	
  PHP_EOL	
  );
       	
  	
  	
  	
  fwrite(	
  STDERR,	
  "033[1A");	
  //Move	
  up,	
  undo	
  the	
  PHP_EOL
       	
  	
  	
  	
  usleep(	
  100000	
  );
       }




Sunday, March 3, 13
ONE STEP FURTHER!




Sunday, March 3, 13
fwrite(	
  STDERR,	
  "Are	
  you	
  sure	
  (y/n):	
  "	
  );
       if(	
  fread(	
  STDIN,	
  1	
  )	
  !=	
  'y'	
  )	
  {	
  die(1);	
  }

       fwrite(	
  STDOUT,	
  "0337"	
  );	
  //	
  Save	
  Position
       for($i	
  =	
  0;	
  $i	
  <=	
  100;	
  $i	
  +=	
  5)	
  {
       	
  	
  	
  	
  $step	
  =	
  intval($i	
  /	
  10);
       	
  	
  	
  	
  fwrite(	
  STDERR,	
  "0338");	
  //	
  Restore	
  Position
       	
  	
  	
  	
  fwrite(	
  STDERR,	
  "[033[32m"	
  .	
  str_repeat('#',	
  $step)	
  .	
  str_repeat('.',	
  10	
  -­‐	
  $step)	
  .	
  "033[0m]"	
  );	
  //	
  Write	
  Progress	
  Bar
       	
  	
  	
  	
  fwrite(	
  STDOUT,	
  "	
  {$i}%	
  Complete"	
  .	
  PHP_EOL	
  );
       	
  	
  	
  	
  fwrite(	
  STDERR,	
  "033[1A");	
  //Move	
  up,	
  undo	
  the	
  PHP_EOL
       	
  	
  	
  	
  usleep(	
  100000	
  );
       }

       fwrite(	
  STDERR,	
  "007"	
  );	
  //Bell	
  on	
  completion

       fwrite(	
  STDERR,	
  PHP_EOL	
  );




Sunday, March 3, 13
MORE PROGRESS BARS!

    • CLI-Toolkit         StatusGUI ProgressBar

         • bit.ly/cli-tk                    github.com/donatj/CLI-Toolkit




    • PEAR            Console_ProgressBar

         •   bit.ly/pear-pb                 pear.php.net/package/Console_ProgressBar



Sunday, March 3, 13
UTF-8 BOX DRAWING
                         CHARACTERS
                                               ┌─┬┐	
  	
  ╔═╦╗	
  	
  ╓─╥╖	
  	
  ╒═╤╕
                                               │	
  ││	
  	
  ║	
  ║║	
  	
  ║	
  ║║	
  	
  │	
  ││
                                               ├─┼┤	
  	
  ╠═╬╣	
  	
  ╟─╫╢	
  	
  ╞═╪╡
                                               └─┴┘	
  	
  ╚═╩╝	
  	
  ╙─╨╜	
  	
  ╘═╧╛
                                               ┌───────────────────┐
                                               │	
  	
  ╔═══╗	
  SOME	
  TEXT	
  	
  │
                                               │	
  	
  ╚═╦═╝	
  IN	
  THE	
  BOX	
  │
                                               ╞═╤══╩══╤═══════════╡
                                               │	
  ├──┬──┤	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  │
                                               │	
  └──┴──┘	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  │
                                               └───────────────────┘


                                            U+258x	
  ▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏
                                            U+259x▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟


    bit.ly/boxchars          en.wikipedia.org/wiki/Box-drawing_character
Sunday, March 3, 13
EXAMPLES




Sunday, March 3, 13
Sunday, March 3, 13
https://github.com/donatj/Pinch
Sunday, March 3, 13
THINGS TO LOOK AT

    • PHAR            for Redistribution

    • PHP-CLI.com

    • CLI Toolkit         - bit.ly/cli-tk
        github.com/donatj/CLI-Toolkit

    • Symfony           2 - bit.ly/cli-sf
        github.com/symfony/symfony/tree/master/src/Symfony/Component/Console



Sunday, March 3, 13
CLOSING

                                joind.in/8231

                      Code Samples: bit.ly/bpcs-samples

                              donatstudios.com

                             github.com/donatj

                                  @donatj

                             donatj on freenode




Sunday, March 3, 13

Mais conteúdo relacionado

Mais procurados

Bash and regular expressions
Bash and regular expressionsBash and regular expressions
Bash and regular expressionsplarsen67
 
Module 03 Programming on Linux
Module 03 Programming on LinuxModule 03 Programming on Linux
Module 03 Programming on LinuxTushar B Kute
 
De 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKDe 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKAdolfo Sanz De Diego
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaLin Yo-An
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Zyxware Technologies
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1兎 伊藤
 
Unix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaUnix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaiCreateWorld
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basicsAbhay Sapru
 
Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Ben Pope
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentationbrian_dailey
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script ProgrammingLin Yo-An
 
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...alessandro mazzoli
 
Best training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingBest training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingvibrantuser
 
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindiaComplaints
 

Mais procurados (18)

Bash and regular expressions
Bash and regular expressionsBash and regular expressions
Bash and regular expressions
 
Module 03 Programming on Linux
Module 03 Programming on LinuxModule 03 Programming on Linux
Module 03 Programming on Linux
 
How to get help in R?
How to get help in R?How to get help in R?
How to get help in R?
 
De 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKDe 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWK
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 
Unix shell scripting
Unix shell scriptingUnix shell scripting
Unix shell scripting
 
Php 2
Php 2Php 2
Php 2
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1
 
Unix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaUnix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU Karnataka
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Getfilestruct zbksh(1)
Getfilestruct zbksh(1)Getfilestruct zbksh(1)
Getfilestruct zbksh(1)
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
Unix lab manual
Unix lab manualUnix lab manual
Unix lab manual
 
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
QNlocal: Docker, Continuous Integration, WordPress e milioni di visite. Si è ...
 
Best training-in-mumbai-shell scripting
Best training-in-mumbai-shell scriptingBest training-in-mumbai-shell scripting
Best training-in-mumbai-shell scripting
 
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on php
 

Destaque

Trilliumbridgeehealthforum gautam
Trilliumbridgeehealthforum gautam Trilliumbridgeehealthforum gautam
Trilliumbridgeehealthforum gautam gautam-neeraj
 
TDC SP 2015 - PHP7: melhor e mais rápido
TDC SP 2015 - PHP7: melhor e mais rápidoTDC SP 2015 - PHP7: melhor e mais rápido
TDC SP 2015 - PHP7: melhor e mais rápidoBruno Ricardo Siqueira
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情Junichi Ishida
 
A 7 architecture sustaining line live
A 7 architecture sustaining line liveA 7 architecture sustaining line live
A 7 architecture sustaining line liveLINE Corporation
 
リアルタイム画風変換とその未来
リアルタイム画風変換とその未来リアルタイム画風変換とその未来
リアルタイム画風変換とその未来LINE Corporation
 
микрогранты для встречи с участниками 10.02.2017 fin
микрогранты для встречи с участниками 10.02.2017 finмикрогранты для встречи с участниками 10.02.2017 fin
микрогранты для встречи с участниками 10.02.2017 finThe Skolkovo Foundation
 
Нейронечёткая классификация слабо формализуемых данных | Тимур Гильмуллин
Нейронечёткая классификация слабо формализуемых данных | Тимур ГильмуллинНейронечёткая классификация слабо формализуемых данных | Тимур Гильмуллин
Нейронечёткая классификация слабо формализуемых данных | Тимур ГильмуллинPositive Hack Days
 
強化学習その3
強化学習その3強化学習その3
強化学習その3nishio
 
先端技術とメディア表現1 #FTMA15
先端技術とメディア表現1 #FTMA15先端技術とメディア表現1 #FTMA15
先端技術とメディア表現1 #FTMA15Yoichi Ochiai
 
データ分析を支えるクローリング環境の構築
データ分析を支えるクローリング環境の構築データ分析を支えるクローリング環境の構築
データ分析を支えるクローリング環境の構築LINE Corporation
 

Destaque (14)

Trilliumbridgeehealthforum gautam
Trilliumbridgeehealthforum gautam Trilliumbridgeehealthforum gautam
Trilliumbridgeehealthforum gautam
 
TDC SP 2015 - PHP7: melhor e mais rápido
TDC SP 2015 - PHP7: melhor e mais rápidoTDC SP 2015 - PHP7: melhor e mais rápido
TDC SP 2015 - PHP7: melhor e mais rápido
 
PHP e seus demônios
PHP e seus demôniosPHP e seus demônios
PHP e seus demônios
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
 
Excel
ExcelExcel
Excel
 
Design patterns de uma vez por todas
Design patterns de uma vez por todasDesign patterns de uma vez por todas
Design patterns de uma vez por todas
 
A 7 architecture sustaining line live
A 7 architecture sustaining line liveA 7 architecture sustaining line live
A 7 architecture sustaining line live
 
リアルタイム画風変換とその未来
リアルタイム画風変換とその未来リアルタイム画風変換とその未来
リアルタイム画風変換とその未来
 
микрогранты для встречи с участниками 10.02.2017 fin
микрогранты для встречи с участниками 10.02.2017 finмикрогранты для встречи с участниками 10.02.2017 fin
микрогранты для встречи с участниками 10.02.2017 fin
 
Нейронечёткая классификация слабо формализуемых данных | Тимур Гильмуллин
Нейронечёткая классификация слабо формализуемых данных | Тимур ГильмуллинНейронечёткая классификация слабо формализуемых данных | Тимур Гильмуллин
Нейронечёткая классификация слабо формализуемых данных | Тимур Гильмуллин
 
強化学習その3
強化学習その3強化学習その3
強化学習その3
 
先端技術とメディア表現1 #FTMA15
先端技術とメディア表現1 #FTMA15先端技術とメディア表現1 #FTMA15
先端技術とメディア表現1 #FTMA15
 
データ分析を支えるクローリング環境の構築
データ分析を支えるクローリング環境の構築データ分析を支えるクローリング環境の構築
データ分析を支えるクローリング環境の構築
 

Semelhante a Beautiful PHP CLI Scripts

Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data typesJames Wong
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)Chhom Karath
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottO'Reilly Media
 
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);Joel Porquet
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Arthur Puthin
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkChristian Trabold
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Migrating to Puppet 4.0
Migrating to Puppet 4.0Migrating to Puppet 4.0
Migrating to Puppet 4.0Puppet
 

Semelhante a Beautiful PHP CLI Scripts (20)

Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
Easy R
Easy REasy R
Easy R
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Migrating to Puppet 4.0
Migrating to Puppet 4.0Migrating to Puppet 4.0
Migrating to Puppet 4.0
 
03 tk2123 - pemrograman shell-2
03   tk2123 - pemrograman shell-203   tk2123 - pemrograman shell-2
03 tk2123 - pemrograman shell-2
 

Beautiful PHP CLI Scripts

  • 1. ________ __________________ ______ ___ __ )__________ ____ ___ /___(_)__ __/___ ____ / __ __ | _ __ `/ / / / __/_ /__ /_ _ / / /_ / _ /_/ // __/ /_/ // /_/ // /_ _ / _ __/ / /_/ /_ / /_____/ ___/__,_/ __,_/ __/ /_/ /_/ __,_/ /_/ ______ _ _ ______ _______ _ _ ______ _ (_____ (_) (_|_____ (_______|_) | | / _____) (_) _ _____) )______ _____) ) _ _ | | ( (____ ____ ____ _ ____ _| |_ ___ | ____/ ___ | ____/ | | | | | | ____ / ___)/ ___) | _ (_ _)/___) | | | | | | | | |_____| |_____| | _____) | (___| | | | |_| || |_|___ | |_| |_| |_|_| ______)_______)_| (______/ ____)_| |_| __/ __|___/ |_| Jesse G. Donat <donatj@gmail.com> donatstudios.com github.com/donatj @donatj Sunday, March 3, 13
  • 2. ABOUT ME • Programming Professional for 7 years. • First computer was a monochrome Epson running DOS 3.22 • Started programming at age 11 (QBasic) • Works for Capstone Digital • Spent my 21st birthday in a Japanese Police Department Sunday, March 3, 13
  • 3. WHAT? Using PHP as a Shell Script, while making it both useful and visually appealing. That’s What! UNIX Like Sorry, Windows Developers :( High Level Skim Sunday, March 3, 13
  • 4. WHY COMMAND LINE? Why not? Data Processing Long Running Processes Tools / Utilities Component Testing Sunday, March 3, 13
  • 5. WHY PHP? Why not? Familiarity Flexibility Ease of Use Code Reuse Sunday, March 3, 13
  • 6. EXAMPLES Composer PHPUnit phpDocumentor Phing Sunday, March 3, 13
  • 8. <?php echo  "Hello  World!"; echo  PHP_EOL; GOOD ENOUGH? Sunday, March 3, 13
  • 9. <?php echo  "Hello  World!"; echo  PHP_EOL; WE CAN DO BETTER! #!/usr/bin/env  php <?php fwrite(  STDOUT,  "Hello  World!"  ); fwrite(  STDOUT,  PHP_EOL  ); Sunday, March 3, 13
  • 10. #! ??? • Known as shebang, hash-bang, pound-bang, etc • “Interpreter Directive” • Absolute path • #!/usr/bin/php • #!/usr/bin/env php • More portable • Executes from your $PATH • Script must be set executable • chmod +x my_awesome_script.php Sunday, March 3, 13
  • 11. OTHER NOTES When using hash-bang, must use UNIX linefeeds Make sure max_execution_time not overridden as included frameworks may reset this. Sunday, March 3, 13
  • 12. SYSTEM CALLS • `call` - Backtick operator • passthru( string $command [, int &$return_var ] ) • Returns result as string • Sends result directly to output • Easy, least flexible. • Second parameter is the status code • Can be difficult to spot in code. • shell_exec( string $cmd ) • Identical to the Backtick operator • exec( string $command [, array &$output [, int &$return_var ]] ) • Returns only the last line of the result • Entire output is retrieved by reference through the second parameter • Third parameter is the status code by reference Sunday, March 3, 13
  • 13. PROCESS CONTROL • proc_* php.net/manual/en/function.proc-open.php • Good for long running external commands where you want to parse the output in real time • Complicated to use Sunday, March 3, 13
  • 14. define('BUF_SIZ',    20);          #  max  buffer  size define('FD_WRITE',  0);            #  STDIN define('FD_READ',    1);            #  STDOUT define('FD_ERR',      2);            #  STANDARDERROR function  proc_exec($cmd)  {        $descriptorspec  =  array(                0  =>  array("pipe",  "r"),                1  =>  array("pipe",  "w"),                2  =>  array("pipe",  "w")        );        $ptr  =  proc_open($cmd,  $descriptorspec,  $pipes);        if  (!is_resource($ptr))                return  false;        while  (($buffer  =  fgets($pipes[FD_READ],  BUF_SIZ))  !=  NULL                          ||  ($errbuf  =  fgets($pipes[FD_ERR],  BUF_SIZ))  !=  NULL)  {                if  (!isset($flag))  {                        $pstatus  =  proc_get_status($ptr);                        $first_exitcode  =  $pstatus["exitcode"];                        $flag  =  true;                }                if  (strlen($buffer))  fwrite(STDOUT,  $buffer);                if  (strlen($errbuf))  fwrite(STDERR,  "ERR:  "  .  $errbuf);        }        foreach  ($pipes  as  $pipe)  {  fclose($pipe);  }        /*  Get  the  expected  *exit*  code  to  return  the  value  */        $pstatus  =  proc_get_status($ptr);        if  (!strlen($pstatus["exitcode"])  ||  $pstatus["running"])  {                /*  we  can  trust  the  retval  of  proc_close()  */                if  ($pstatus["running"])                        proc_terminate($ptr);                $ret  =  proc_close($ptr);        }  else  {                if  ((($first_exitcode  +  256)  %  256)  ==  255                                  &&  (($pstatus["exitcode"]  +  256)  %  256)  !=  255)                        $ret  =  $pstatus["exitcode"];                elseif  (!strlen($first_exitcode))                        $ret  =  $pstatus["exitcode"];                elseif  ((($first_exitcode  +  256)  %  256)  !=  255)                        $ret  =  $first_exitcode;                else                        $ret  =  0;  /*  we  "deduce"  an  EXIT_SUCCESS  ;)  */                proc_close($ptr);        }        return  ($ret  +  256)  %  256; } Sunday, March 3, 13
  • 15. TERMINAL INFORMATION tput makes a very good friend! Size in columns tput cols Size in rows tput lines Supported tput colors Number of Colors $rows  =  intval(`tput  lines`); $cols  =  intval(`tput  cols`); echo  "Your  terminal  is  {$rows}x{$cols}!"; Sunday, March 3, 13
  • 18. STANDARD STREAMS Standard Output Standard Error Standard Input STDOUT STDERR STDIN The main application output to A second output stream to The main input stream into a the terminal. the terminal. program. Stream most easily piped for Useful for error messages as Generally directly from the logging or secondary well as control codes and end users keyboard unless processing. other you wouldn’t want otherwise piped. sent to a piped output. Sunday, March 3, 13
  • 19. STANDARD OUT NOTES • echo “Hello World!”; • php://output is not necessarily standard out • Susceptible to output buffering • fwrite( STDOUT, "Hello World!" ); • More explicit! Sunday, March 3, 13
  • 20. READING STANDARD IN Its just like reading from a file, very slowly. fwrite(  STDERR,  "Are  you  sure  (y/n):  "  ); while(  $line  =  fgets(  STDIN  )  )  { if(  fread(  STDIN,  1  )  ==  'y'  )  {    fwrite(  STDOUT,  $line  );        fwrite(  STDOUT,  "Super  Cool!"  ); } }else{        fwrite(  STDOUT,  "LAME!"  ); } fwrite(  STDOUT,  PHP_EOL  ); Sunday, March 3, 13
  • 21. COMMAND LINE ARGUMENTS Sunday, March 3, 13
  • 22. BASIC ARGUMENTS • Global $argv • Useful for simple single scripts accepting a small • First argument is always the number of parameters executed script Sunday, March 3, 13
  • 23. COMPLEX ARGUMENTS $shortopts    =  "r:";    //  Required  value $shortopts  .=  "o::";  //  Optional  value $shortopts  .=  "abc";  //  These  options  do  not  accept  values $longopts      =  array(        "reqval:",              //  Has  a  value        "optval::",            //  Optional  value        "noval",                  //  No  value ); $options  =  getopt($shortopts,  $longopts); var_dump($options); Sunday, March 3, 13
  • 24. FURTHER INFORMATION Other Simple Operations Is the code running $is_cli  =  substr(php_sapi_name(),  0,  3)  ==  'cli'; in the CLI? Is a stream $is_piped  =  !posix_isatty(STDOUT); being piped? Sunday, March 3, 13
  • 25. CONTROL CODES It’s about to get good! Sunday, March 3, 13
  • 26. • More are prefixed with the ASCII “Escape” character: “033” • Let you control terminal behaviors and format output. • Cursor Control (Positioning Text) • Colors • Erasing (Screen, Lines, Etc) • Raise a “Bell” • More! • bit.ly/controlcodes www.termsys.demon.co.uk/vtansi.htm Sunday, March 3, 13
  • 27. CURSOR CONTROL Up 033[{COUNT}A Down 033[{COUNT}B Forward (Right) 033[{COUNT}C Backwards (Left) 033[{COUNT}D Force Position 033[{ROW};{COLUMN}f Save 0337 Restore 0338 Sunday, March 3, 13
  • 28. ERASING Erase Screen 033[2J Current Line 033[2K Current Line UP 033[1J Current Line Down 033[J To Start of Line 033[1K To End of Line 033[K Sunday, March 3, 13
  • 29. COLORS! • Standard 8-Color Set • Black / Red / Green / Yellow / Blue / Magenta / Cyan / White • Extended xterm-256 Color Set • Not Well Supported Detection! #!/usr/bin/env  php <?php $colors  =  max(8,  intval(`tput  colors`)); fwrite(  STDOUT,  "Terminal  supports  {$colors}  colors!"  ); fwrite(  STDOUT,  PHP_EOL  ); Sunday, March 3, 13
  • 30. Great for warnings (red!) Great for separating ideas. Hated by UNIX beards world over Sunday, March 3, 13
  • 31. STANDARD STYLING Attribute Code 033[{attributes separated by semicolon}m Reset All 0 Bright (Bold) 1 fwrite(  STDOUT,  "033[31m"      .  "Red  Text"                                .  PHP_EOL  ); Dim 2 fwrite(  STDOUT,  "033[4m"        .  "Red  And  Underlined  Text"  .  PHP_EOL  ); fwrite(  STDOUT,  "033[0m"        .  "Normal  Text"                          .  PHP_EOL  ); Underline 4 fwrite(  STDOUT,  "033[31;4m"  .  "Red  and  Underlined  Text"  .  PHP_EOL  ); Blink 5 Reverse (Inverted) 7 Hidden 8 Color Foreground Code Background Code Black 30 40 Red 31 41 Green 32 42 Yellow 33 43 Blue 34 44 Magenta 35 45 Cyan 36 46 White 37 47 Sunday, March 3, 13
  • 32. RESET! EOL AT THE END! Sunday, March 3, 13
  • 33. OTHER NOTES • Best Practice: send all control codes to standard error • “007” is the ASCII Bell Character • PHP errors by default output to standard out, not standard error • Status Codes • Let the world outside your script know there was a problem • die(1); //non-zero implies error Sunday, March 3, 13
  • 35. for($i  =  0;  $i  <=  100;  $i  +=  5)  {        fwrite(  STDOUT,  "{$i}%  Complete"  .  PHP_EOL  );        usleep(  100000  ); } Sunday, March 3, 13
  • 36. fwrite(  STDOUT,  "0337"  );  //  Save  Position for($i  =  0;  $i  <=  100;  $i  +=  5)  {        fwrite(  STDOUT,  "0338"  .  "{$i}%  Complete"  );  //  Restore  Position  and  Write  Percentage        usleep(  100000  ); } fwrite(  STDOUT,  PHP_EOL  ); Sunday, March 3, 13
  • 37. fwrite(  STDOUT,  "0337"  );  //  Save  Position for($i  =  0;  $i  <=  100;  $i  +=  5)  {        $step  =  intval($i  /  10);        fwrite(  STDERR,  "0338");  //  Restore  Position        fwrite(  STDERR,  '['  .  str_repeat('#',  $step)  .  str_repeat('.',  10  -­‐  $step)  .  ']'    );  //  Write  Progress  Bar        fwrite(  STDOUT,  "  {$i}%  Complete"  .  PHP_EOL  );        fwrite(  STDERR,  "033[1A");  //Move  up,  undo  the  PHP_EOL        usleep(  100000  ); } Sunday, March 3, 13
  • 39. fwrite(  STDERR,  "Are  you  sure  (y/n):  "  ); if(  fread(  STDIN,  1  )  !=  'y'  )  {  die(1);  } fwrite(  STDOUT,  "0337"  );  //  Save  Position for($i  =  0;  $i  <=  100;  $i  +=  5)  {        $step  =  intval($i  /  10);        fwrite(  STDERR,  "0338");  //  Restore  Position        fwrite(  STDERR,  "[033[32m"  .  str_repeat('#',  $step)  .  str_repeat('.',  10  -­‐  $step)  .  "033[0m]"  );  //  Write  Progress  Bar        fwrite(  STDOUT,  "  {$i}%  Complete"  .  PHP_EOL  );        fwrite(  STDERR,  "033[1A");  //Move  up,  undo  the  PHP_EOL        usleep(  100000  ); } fwrite(  STDERR,  "007"  );  //Bell  on  completion fwrite(  STDERR,  PHP_EOL  ); Sunday, March 3, 13
  • 40. MORE PROGRESS BARS! • CLI-Toolkit StatusGUI ProgressBar • bit.ly/cli-tk github.com/donatj/CLI-Toolkit • PEAR Console_ProgressBar • bit.ly/pear-pb pear.php.net/package/Console_ProgressBar Sunday, March 3, 13
  • 41. UTF-8 BOX DRAWING CHARACTERS ┌─┬┐    ╔═╦╗    ╓─╥╖    ╒═╤╕ │  ││    ║  ║║    ║  ║║    │  ││ ├─┼┤    ╠═╬╣    ╟─╫╢    ╞═╪╡ └─┴┘    ╚═╩╝    ╙─╨╜    ╘═╧╛ ┌───────────────────┐ │    ╔═══╗  SOME  TEXT    │ │    ╚═╦═╝  IN  THE  BOX  │ ╞═╤══╩══╤═══════════╡ │  ├──┬──┤                      │ │  └──┴──┘                      │ └───────────────────┘ U+258x  ▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏ U+259x▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟ bit.ly/boxchars en.wikipedia.org/wiki/Box-drawing_character Sunday, March 3, 13
  • 45. THINGS TO LOOK AT • PHAR for Redistribution • PHP-CLI.com • CLI Toolkit - bit.ly/cli-tk github.com/donatj/CLI-Toolkit • Symfony 2 - bit.ly/cli-sf github.com/symfony/symfony/tree/master/src/Symfony/Component/Console Sunday, March 3, 13
  • 46. CLOSING joind.in/8231 Code Samples: bit.ly/bpcs-samples donatstudios.com github.com/donatj @donatj donatj on freenode Sunday, March 3, 13