symfony ile command line uygulama geliştirme
TRANSCRIPT
Symfony & Cli App
Symfony ile Commandline Uygulama Geliştirmek
Neden?
Php ile commanline uygulama geliştirebilirsiniz
Ancak bu commandline uygulamaları Php ile
geliştirmeniz için bir tavsiye değildir.
Temel Yöntemler
http://php.net/manual/en/features.commandline.php
Popüler Araçlar ve Yöntemler
1. phar
2. composer
3. symfony/console
PHAR
(PHP Archive)
1. PHAR (PHP Archive)
Bir PHP ugulamasındaki tüm dosyaları tek bir
dosyada toplayarak “easy distribution”
sağlayan arşivleme metodu
http://us1.php.net/manual/en/book.phar.php
Phar: Kurulum & Ayar
Built-in >= PHP v5.3.0
Pecl Extension < PHP v5.3.0
php.ini : phar.readonly = 0
Phar: Paketleme
$sourcePath = "./src";$buildPath = "./build";
$phar = new Phar($buildPath . "/app.phar", FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, "app.phar");$phar["index.php"] = file_get_contents($srcRoot . "/index.php");$phar["helper.php"] = file_get_contents($srcRoot . "/helper.php");$phar->setStub($phar->createDefaultStub("index.php"));
Composer
Composer: Kurulum
Curl ile$ curl -sS https://getcomposer.org/installer | php
Php ile$ php -r "readfile('https://getcomposer.org/installer');" | php
Source https://getcomposer.org/download/
Composer: composer init
$ composer init
Composer: composer.json
{"name": "okulbilisim/sample","description": "Sample composer project","require": {
"guzzle/guzzle": "~3.9@dev"},"license": "MIT","authors": [
{"name": "hasantayyar","email": "[email protected]"
}],"minimum-stability": "dev"
}
Composer: bin folder
{"bin": ["bin/script_demo", "bin/other_script_demo"]
}
symfony/console
3. symfony/console
symfony/console
"require": {
"php": ">=5.4.1",
"symfony/console": "2.4.x-dev"
}
$ composer install
$ touch console && chmod +x console
$ echo "#/usr/bin/env php" > console
$ ./console
time_limit
#!/usr/bin/env php<?phpset_time_limit(0);
timezone
#!/usr/bin/env php<?phpset_time_limit(0);date_default_timezone_set('Europe/Istanbul');
Sf Console: hello
#!/usr/bin/env php<?phpset_time_limit(0);date_default_timezone_set('Europe/Istanbul');require_once __DIR__ . '/vendor/autoload.php';use Symfony\Component\Console\Application;$app = new Application();$app->run();
Sf Console: Default Command
use Symfony\Component\Console\Application;use Demo\Commands\HelloCommand;
$command = new HelloCommand();$app = new Application();$application->setDefaultCommand($command->getName());$application->run();
Sf Console: input
Option & Argument
./console say:hello jesus --yell
Sf Console: input
Option & Argument
./console say:hello jesus --yellcommand arg. option
use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Input\InputArgument;use Symfony\Component\Console\Input\InputOption;
Sf Console: input / arguments
…->addArgument(
'name',InputArgument::OPTIONAL, // InputArgument::REQUIRED | InputArgument::IS_ARRAY'Who do you want to say hello?'
)
Sf Console: input / options
…->addOption(
'yell',null,InputOption::VALUE_NONE,/*InputOption::VALUE_IS_ARRAY , InputOption::VALUE_NONEInputOption::VALUE_REQUIRED , InputOption::VALUE_OPTIONAL*/'ALL CAPS'
)
Sf Console: output
use Symfony\Component\Console\Output\OutputInterface;
Sf Console: Renklendirme
$output->writeln('<info>foo</info>');
$output->writeln('<comment>foo</comment>');
$output->writeln('<question>foo</question>');
$output->writeln('<error>foo</error>');
Sf Console: Renklendirme
$style = new OutputFormatterStyle('red', 'yellow', array('bold', 'blink'));
$output->getFormatter()->setStyle('yanyan', $style);
$output->writeln('<yanyan>yanmalı</yanyan>');
Sf Console: Renklendirme
$output->writeln('<fg=black;bg=cyan;options=bold>'.'ateşli'.'</fg=black;bg=cyan;options=bold>');
Sf Console: Helpers
1. Question Helper
2. Formatter Helper
3. ProgressBar
4. Table
Sf Console: Question Helper
use Symfony\Component\Console\Question\ConfirmationQuestion;$helper = $this->getHelper('question');
$helper = $this->getHelper('question');$question = new ConfirmationQuestion('Continue with this action?', false);
if (!$helper->ask($input, $output, $question)) {return;
}
Sf Console: Question Helper
use Symfony\Component\Console\Question\ChoiceQuestion;
$helper = $this->getHelper('question');$question = new ChoiceQuestion(
'Please select your favorite color (defaults to red)',array('red', 'blue', 'yellow'),0
);$question->setErrorMessage('Color %s is invalid.');$color = $helper->ask($input, $output, $question);$output->writeln('You have just selected: '.$color);
Sf Console: Question Helper
// Autocomplete
$bundles = array('AcmeDemoBundle', 'AcmeBlogBundle', 'AcmeStoreBundle');$question = new Question('Please enter the name of a bundle', 'FooBundle');$question->setAutocompleterValues($bundles);
Sf Console: Question Helper
// Hidden input
$question->setHidden(true);$question->setHiddenFallback(false);
Sf Console: Question Helper
// Validation
$question->setValidator(function ($answer) {if (strlen($answer)<10 ) {throw new \RuntimeException(
'The answer is too short');}
return $answer;});$question->setMaxAttempts(2);$name = $helper->ask($input, $output, $question);
Çıktı renklendirmesini özelleştirmek için kullanılır.
$formatter = $this->getHelper('formatter');$formattedLine = $formatter->formatSection('Adım 1','Bu adımla ilgili metin');$output->writeln($formattedLine);
[Adım 1] Bu adımla ilgili metin .
Sf Console: Formatter Helper
$errorMsg = array('Error!', 'Hata olustu');$block = $formatter->formatBlock($errorMsg, 'error');$output->writeln($block);
Sf Console: Formatter Helper
[Error!]Hata Oluştu
Sf Console: Progress Helper
Progress bar göstermek için
use Symfony\Component\Console\Helper\ProgressBar;$progress = new ProgressBar($output, 50);$progress->start();$i = 0;while($i++ < 50) {
$progress->advance();$progress->finish();
}
Sf Console: Table Helper
use Symfony\Component\Console\Helper\Table;
$table = new Table($output);
$table->setHeaders(array('ISBN', 'Title', 'Author'))->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
));
$table->render();
Sf Console: Table Helper
use Symfony\Component\Console\Helper\Table;use Symfony\Component\Console\Helper\TableSeparator;
$table->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),new TableSeparator(),array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
));
Sf Console: Table Helper
use Symfony\Component\Console\Helper\Table;
$table->setStyle('default');//$table->setStyle('compact');$table->render();
Sf Console: Table Helper
setPaddingChar()setHorizontalBorderChar()setVerticalBorderChar()setCrossingChar()setCellHeaderFormat()setCellRowFormat()setBorderFormat()setPadType()
Sf Console: Dahası
1. Cli app içinde EventDispatcher kullanılabilir
2. Psr\Log\LoggerInterface
3. $this->getHelper('debug_formatter');
4. $helper = $this->getHelper('process'); // >= symfony 2.6
1. https://github.com/maximebf/ConsoleKit
2. https://github.com/wp-cli/php-cli-tools
3. https://github.com/ulrichsg/getopt-php
4. https://github.com/nette/command-line
5. https://github.com/MrRio/shellwrap
6. https://github.com/g4code/commando
Diğer Paketler
Sorular?
@htayyar
github.com/hasantayyar
hasantayyar.net