PHPコンソールコマンド

私の多くと同様、定期的にいくつかの小さなタスクを実装する必要があります。 たとえば、サイト/ APIを解析し、データをxml / json / csvに保存し、計算/再集計を行い、ある形式から別の形式にデータを追い越し、統計を収集するなど。 など 現在のプロジェクトに関係しないタスクについて話していることに注意してください。







便利な機能のために重いフレームワークを収集するのは面倒で、コード内に現在のプロジェクトを実装するのは見た目が良くありません。 したがって、時間を節約するには、スクリプトを作成し、以前の開発のコードをコピーして貼り付け、さまざまなライブラリを接続して、コンソールからスクリプトを実行する必要があります。 これには、スクリプトの対話性が必要になることがあります。処理オプション/引数、さらには対話の対話です。 ここでの主なことは、「食欲は食事に伴う」という表現でよく説明されているムードがなく、単純なタスクの作業が何をもたらすかはまったく明確ではないということです=)



そのような瞬間、便利なシンフォニーコンソールを思い出しました。

Symfony2。他のコンソール(zend、yii、django、rorなど)に対する違反はありません。すべて問題ありません。



もう一度何かを解析する必要が生じたとき、Symfonyコンソール( Console Component )と、この独立したコンポーネントがますますその機能を使用するように私を押し進めたという事実を思い出しました。



数時間、それは以下に基づいたシンプルなツールであることが判明しました。



Composer依存関係マネージャーは、これらすべてをすばやく収集し、新しいものを追加し、クラスの自動読み込みを処理するのに役立ちます。



最新のニュース、「インターネット」トピックのリストを収集する必要が本当にあったとします。 また、ソースとして、Yandex.News RSSサービスに非常に満足しています。



omposerを使用して、新しいプロジェクトを作成します。

$ composer create-project suncat/console-commands ./cmd
      
      





Composerをグローバルにインストールしているため、いつでも利用できます。 まだ使用していない場合は、サンプルを検証するためにインストールする必要があります。



アプリケーションとすべての依存関係をダウンロードした後、作成されたディレクトリに移動します。

 $ cd cmd #  ,         
      
      





構造は次のとおりです。

 app/ console #  src/ #  psr-0 Command/ #    vendor/ #  
      
      





状態を確認します。

 $ app/console list
      
      





ヘルプ情報と使用可能なコマンドのリストが表示されていれば、すべて問題ありません。 次のようになります。







次に、タスクの実装に使用する予定のコマンドのクラステンプレートを作成します。

 $ app/console generate
      
      





表示されるダイアログで、将来のクラスの名前を指定します。

 Please enter the name of the command class: NewsInternetCommand
      
      





応答として、通知を受け取ります。

 Generated new command class to "./cmd/src/Command/NewsInternetCommand.php"
      
      





実際、チームは準備ができており、利用可能なチームのリストに表示されています。







しかし、彼女は必要なことはしていません(ここで、作成したクラスをIDEまたはお気に入りのエディターで開き、コマンドコードを記述できます)。



この例では、外部コンテンツを受信する必要があり、OOPが好きなので、別のライブラリを配置します。

 $ composer require kriswallsmith/buzz 0.9
      
      





バズはPHP5.3の軽量HTTPクライアントです。 これを使用して、ニュースサービスへのリクエストを処理します。



別のクラス-YandexRSSNewsParserを作成しましょう。YandexRSSNewsParserは、チームに準備されたコンテンツをクラスに提供します。

 // ./src/Parser/YandexRSSNewsParser.php namespace Parser; use Buzz\Client\FileGetContents; use Buzz\Message\Request; use Buzz\Message\Response; use DOMDocument; use DOMXPath; class YandexRSSNewsParser { private $method; private $host; /** * Construct */ public function __construct() { $this->method = 'GET'; $this->host = 'http://news.yandex.ru'; } /** * Get news * * @param $resource * * @return mixed */ public function getNews($resource) { // content $xml = $this->getData($resource); if (false === $xml) { return array(); } $doc = new DOMDocument(); @$doc->loadXML($xml); $xpath = new DOMXpath($doc); // items $items = $xpath->query('.//item'); $news = array(); foreach ($items as $item) { $news[] = array( 'datetime' => $xpath->evaluate("./pubDate", $item)->item(0)->nodeValue, 'title' => $xpath->evaluate("./title", $item)->item(0)->nodeValue ); } return $news; } /** * Get data * * @return mixed */ protected function getData($resource) { $request = new Request($this->method, $resource, $this->host); $response = new Response(); $client = new FileGetContents(); // processing get data $attempt = 0; do { if ($attempt) { sleep($attempt); } try { $client->send($request, $response); } catch (\Exception $e) { continue; } } while (false === ($response instanceof Response) && ++$attempt < 5); if (false === ($response instanceof Response) || false === $response->isOk()) { return false; } $data = $response->getContent(); return $data; } }
      
      





そして、コマンドクラスを編集して、コンソールに最新のニュース見出し、「インターネット」見出しを表示します。

 // ./src/Command/NewsInternetCommand.php namespace Command; use Parser\YandexRSSNewsParser; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * NewsInternetCommand */ class NewsInternetCommand extends Command { /** * Configuration of command */ protected function configure() { $this ->setName("news:internet") ->setDescription("Command for parsing internet news") ; } /** * Execute command * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $parser = new YandexRSSNewsParser(); $output->writeln("<info>Start parsing</info>\n")); // News $news = $parser->getNews('/internet.rss'); foreach ($news as $item) { $output->writeln(sprintf("<info>[%s]</info> <comment>%s</comment>", $item['datetime'], $item['title'])); } $output->writeln("\n<info>Done!</info>")); } }
      
      





準備されたコマンドを実行します。

 $ app/console news:internet
      
      





結果:





非常にシンプルであることが判明しましたが、symfony / consoleおよびcomposerにより、PHPでコンソールコマンドを整理するための柔軟で便利なツールです。



All Articles