Desenvolvendo em php cli

33
Desenvolvendo em PHPCli Thiago Paes – PHPSC Conference 2013

Transcript of Desenvolvendo em php cli

Page 1: Desenvolvendo em php cli

Desenvolvendo  em  PHP-­‐Cli  Thiago  Paes  –  PHPSC  Conference  -­‐  2013  

Page 2: Desenvolvendo em php cli

Thiago Paes

•  Evangelista  PHP  •  Aficcionado  por  código  limpo  e  organizado  •  Membro  do  PHP-­‐SC  •  Programador  PHP  a  10+  

Page 3: Desenvolvendo em php cli

PHP  não  é  somente  Server  Side,    você  pode  fazer  poderosas  aplicações    

rodando  localmente.    

SEM  um  servidor  web.  

Page 4: Desenvolvendo em php cli

VÁ  EM  FRENTE,    PEQUENO  PADAWAN  

Page 5: Desenvolvendo em php cli

$ARGC  &  $ARGV  

Page 6: Desenvolvendo em php cli
Page 7: Desenvolvendo em php cli

FAÇA  DIREITO!!!!  

Page 8: Desenvolvendo em php cli
Page 9: Desenvolvendo em php cli

Symfony Console namespace  Acme\DemoBundle\Command;    use  Symfony\Component\Console\Command\Command;  use  Symfony\Component\Console\Input\InputArgument;  use  Symfony\Component\Console\Input\InputInterface;  use  Symfony\Component\Console\Input\InputOp^on;  use  Symfony\Component\Console\Output\OutputInterface;    class  GreetCommand  extends  Command  {          protected  func^on  configure()          {                  $this                          -­‐>setName('demo:greet')                          -­‐>setDescrip^on('Greet  someone')                          -­‐>addArgument(                                  'name',                                  InputArgument::OPTIONAL,                                  'Who  do  you  want  to  greet?'                          )                          -­‐>addOp^on(                                'yell',                                null,                                InputOp^on::VALUE_NONE,                                'If  set,  the  task  will  yell  in  uppercase  lelers'                          );          }            

…  

Page 10: Desenvolvendo em php cli

Symfony Console  protected  func^on  execute(InputInterface  $input,  OutputInterface  $output)          {                  $name  =  $input-­‐>getArgument('name');                  if  ($name)  {                          $text  =  'Hello  '.$name;                  }  else  {                          $text  =  'Hello';                  }                    if  ($input-­‐>getOp^on('yell'))  {                          $text  =  strtoupper($text);                  }                    $output-­‐>writeln($text);          }  }  

…  

Page 11: Desenvolvendo em php cli
Page 12: Desenvolvendo em php cli

Silex //Bootstrap our Silex application $app = require __DIR__ . '/src/bootstrap.php'; //Include the namespaces of the components we plan to use use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; //Instantiate our Console application $console = new Application('ProjectName', '0.1');

…  

Page 13: Desenvolvendo em php cli

Silex //Register a command to run from the command line //Our command will be started with "./console.php sync" $console->register( 'sync' )   ->setDefinition( array(      //Create a "--test" optional parameter      new InputOption('test', '', InputOption::VALUE_NONE, 'Test mode'),     ) )   ->setDescription('Synchronize with an external data source')   ->setHelp('Usage: <info>./console.php sync [--test]</info>')   ->setCode(     function(InputInterface $input, OutputInterface $output) use ($app)     {       if ($input->getOption('test'))       {         $output->write("\n\tTest Mode Enabled\n\n");       }       $output->write( "Contacting external data source ...\n");       //Do work here       //Example:       //  $app[ 'myExtension' ]->doStuff();     }   ); $console->run();

…  

Page 14: Desenvolvendo em php cli

Silex $> ./console.php ProjectName version ProjectVersion Usage: [options] command [arguments] Options: --help -h Display this help message. --quiet -q Do not output any message. --verbose -v Increase verbosity of messages. --version -V Display this program version. --ansi Force ANSI output. --no-ansi Disable ANSI output. --no-interaction -n Do not ask any interactive question. Available commands: help Displays help for a command list Lists commands sync Synchronize with an external data source

Page 15: Desenvolvendo em php cli
Page 16: Desenvolvendo em php cli

Zend Console

//    modules/applica.on/config/module.config.php  array( 'router' => array( 'routes' => array( // HTTP routes are defined here ) ), 'console' => array( 'router' => array( 'routes' => array( // Console routes go here ) ) ), )

Page 17: Desenvolvendo em php cli
Page 18: Desenvolvendo em php cli

Console Getopt Plus $config = array(       'header' => array('The command xyz is used to...',         'Note that the header and the usage are optional.'),       'usage' => array('--foo', '--bar <arg> -c [arg]'),       'options' => array(         array('long' => 'foo', 'type' => 'noarg', 'desc' => array(           'An option without argument with only the long',           'name defined.')),         array('long' => 'bar', 'type' => 'mandatory', 'short' => 'b',           'desc' => array('arg',             'A mandatory option with both the long and',             'the short names defined.')),         array('short' => 'c', 'type' => 'optional',           'desc' => array('arg',             'An option with an optional argument with only',             'the short name defined.'))),         'parameters' => array('[param1] [param2]',           'Some additional parameters.'),         'footer' => array('Some additional information.',           'Note that the footer is optional.'),     );     $options = Console_Getoptplus::getoptplus($config); 

Page 19: Desenvolvendo em php cli

Console Command Line // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; // create the parser $parser = new Console_CommandLine(array(     'description' => 'zip given files using the php zip module.',     'version'     => '1.0.0' )); // add an option to make the program verbose $parser->addOption(     'verbose',     array(

        'short_name'  => '-v',         'long_name'   => '--verbose',         'action'      => 'StoreTrue',         'description' => 'turn on verbose output'     ) );

…  

Page 20: Desenvolvendo em php cli

Console Command Line // add an option to delete original files after zipping $parser->addOption(     'delete',     array(         'short_name'  => '-d',         'long_name'   => '--delete',         'action'      => 'StoreTrue',         'description' => 'delete original files after zip operation'     ) ); // run the parser try {

    $result = $parser->parse();     // write your program here...     print_r($result->options);     print_r($result->args); } catch (Exception $exc) {     $parser->displayError($exc->getMessage()); }

…  

Page 21: Desenvolvendo em php cli

Console Getargs $config = array(             // Option takes 2 values             'files|images' => array('short' => 'f|i',                     'min' => 2,                     'max' => 2,                     'desc' => 'Set the source and destination image files.'),             // Option takes 1 value             'width' => array('short' => 'w',                  'min' => 1,                  'max' => 1,                  'desc' => 'Set the new width of the image.'),             // Option is a switch             'debug' => array('short' => 'd',                  'max' => 0,                  'desc' => 'Switch to debug mode.'),             // Option takes from 1 to 3 values, using the default value(s) if the arg is not present             'formats' => array('min' => 1,                    'max' => 3,                    'desc' => 'Set the image destination format.',                    'default' => array('jpegbig', 'jpegsmall')),

…  

Page 22: Desenvolvendo em php cli

Console Getargs             // Option takes from 1 to an unlimited number of values             'filters' => array('short' => 'fi',                    'min' => 1,                    'max' => -1,                    'desc' => 'Set the filters to be applied to the image upon conversion.  // The filters will be used in the order they are set.'),             // Option accept 1 value or nothing. If nothing, then the default value is used             'verbose' => array('short' => 'v',                    'min' => 0,                    'max' => 1,                    'desc' => 'Set the verbose level.',                    'default' => 3),             // Parameters. Anything leftover at the end of the command line is added.             CONSOLE_GETARGS_PARAMS => array('min' => 1,                         'max' => 2,                         'desc' =>                         'Set the application parameters.',                         'default' => 'DEFAULT')             );  

$args =& Console_Getargs::factory($config);

…  

Page 23: Desenvolvendo em php cli
Page 24: Desenvolvendo em php cli

eZ  Components  -­‐  ConsoleTools

$input  = new ezcConsoleInput(); $helpOption = $input->registerOption(      new ezcConsoleOption(          'h',         'help'     ) ); Try {     $input->process(); } catch ( ezcConsoleOptionException $e ) {     die( $e->getMessage() ); } if ( $helpOption->value !== false ) {     echo "Help requested."; } else {     echo "No help requested."; }

Page 25: Desenvolvendo em php cli
Page 26: Desenvolvendo em php cli

TORNAR  EXECUTÁVEL  \o/  

Page 27: Desenvolvendo em php cli

#!/usr/bin/env  php  

Page 28: Desenvolvendo em php cli
Page 29: Desenvolvendo em php cli

Ha  Ha  Ha  QUEM  DISSE?  

Page 30: Desenvolvendo em php cli

EMPACOTE!!!!

Page 31: Desenvolvendo em php cli

// create with alias "project.phar" $phar = new Phar('project.phar', 0, 'project.phar'); $phar->buildFromIterator(     new RecursiveIteratorIterator(      new RecursiveDirectoryIterator('/path/to/project')),     '/path/to/project'); $phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

Page 32: Desenvolvendo em php cli

Dúvidas?  

Page 33: Desenvolvendo em php cli

Obrigado  

•  E-­‐mail:  [email protected]  •  Twiler:  @mrprompt  •  Blog:  hlp://mrprompt.blogspot.com  •  Mais:  hlp://about.me/mrprompt