Desenvolvendo em php cli
-
Upload
thiago-paes -
Category
Technology
-
view
12.129 -
download
2
Transcript of Desenvolvendo em php cli
Desenvolvendo em PHP-‐Cli Thiago Paes – PHPSC Conference -‐ 2013
Thiago Paes
• Evangelista PHP • Aficcionado por código limpo e organizado • Membro do PHP-‐SC • Programador PHP a 10+
PHP não é somente Server Side, você pode fazer poderosas aplicações
rodando localmente.
SEM um servidor web.
VÁ EM FRENTE, PEQUENO PADAWAN
$ARGC & $ARGV
FAÇA DIREITO!!!!
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' ); }
…
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); } }
…
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');
…
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();
…
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
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 ) ) ), )
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);
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' ) );
…
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()); }
…
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')),
…
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);
…
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."; }
TORNAR EXECUTÁVEL \o/
#!/usr/bin/env php
Ha Ha Ha QUEM DISSE?
EMPACOTE!!!!
// 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'));
Dúvidas?
Obrigado
• E-‐mail: [email protected] • Twiler: @mrprompt • Blog: hlp://mrprompt.blogspot.com • Mais: hlp://about.me/mrprompt