LoginSignup
11
10

More than 5 years have passed since last update.

phalcon phpのincubatorでcurlを使ったバッチ処理(Task)を書いてみる

Last updated at Posted at 2015-05-06

概要

phalcon phpの検証中です。
curlを使ったhttpリクエストとかってどうやるんだろ?と思い、調べてみました。
公式ドキュメントを見ると、Requestクラスは存在するのですが、
これはリクエストパラメータの取得だったりを担うモノでどうも違うなと。
で、phalconのgithubを見たところ、incubatorというライブラリがあるようで。

サンプル用のプロジェクトを作成

ここでは「sample-phalcon」という名称でプロジェクトを作成します。

$ phalcon project sample-phalcon

Phalcon DevTools (1.3.4)


  Success: Controller "index" was successfully created.


  Success: Project 'sample-phalcon' was successfully created.

incubatorのインストール

自分の環境のphalconがver1.x系なので、READMEに従ってver1.3.5を入れてみる。

$ cd sample-phalcon/
$ curl -sS https://getcomposer.org/installer | php
$ vim composer.json
$ cat composer.json
{
  "require": {
    "phalcon/incubator": "~1.3.5"
  }
}
$ php composer.phar install

Bootstrap(cli.php)を書く

バッチ(Task)実行用のBootstrapを書く。
書き方は公式ドキュメントに記載がある。
これに、incubatorのREADMEに記載のライブラリ読み込みを追記すればOK

$ vim app/cli.php
cli.php
<?php

 use Phalcon\DI\FactoryDefault\CLI as CliDI,
     Phalcon\CLI\Console as ConsoleApp;

 define('VERSION', '1.0.0');

 //Using the CLI factory default services container
 $di = new CliDI();

 // Define path to application directory
 defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', realpath(dirname(__FILE__)));

 /**
  * Register the autoloader and tell it to register the tasks directory
  */
 $loader = new \Phalcon\Loader();
 $loader->registerDirs(
     array(
         APPLICATION_PATH . '/tasks'
     )
 );

$loader->registerNamespaces(array(
    'Phalcon' => __DIR__.'/../vendor/phalcon/incubator/Library/Phalcon/',
));

 $loader->register();

 // Load the configuration file (if any)
 if(is_readable(APPLICATION_PATH . '/config/config.php')) {
     $config = include APPLICATION_PATH . '/config/config.php';
     $di->set('config', $config);
 }

 //Create a console application
 $console = new ConsoleApp();
 $console->setDI($di);

 /**
 * Process the console arguments
 */
 $arguments = array();
 foreach($argv as $k => $arg) {
     if($k == 1) {
         $arguments['task'] = $arg;
     } elseif($k == 2) {
         $arguments['action'] = $arg;
     } elseif($k >= 3) {
        $arguments['params'][] = $arg;
     }
 }

 // define global constants for the current task and action
 define('CURRENT_TASK', (isset($argv[1]) ? $argv[1] : null));
 define('CURRENT_ACTION', (isset($argv[2]) ? $argv[2] : null));

 try {
     // handle incoming arguments
     $console->handle($arguments);
 }
 catch (\Phalcon\Exception $e) {
     echo $e->getMessage();
     exit(255);
 }

Taskクラスを作成

処理を実行するTaskクラスを作成する。
Http ClientのRequestクラスの使い方はREADMEに書いてある。

$ mkdir -p app/tasks
$ vim app/tasks/RequestsampleTask.php
RequestsampleTask.php
<?php

use Phalcon\Http\Client\Request;

class RequestSampleTask extends \Phalcon\CLI\Task
{
    const RSS_URL = 'http://feeds.feedburner.com/mtl/feed';

    public function mainAction() {

        $response = $this->getResponse(self::RSS_URL);
        $response = $this->parseResponse($response);

        print_r($response);
    }

    private function getResponse($url) {

        $provider  = Request::getProvider();
        $provider->setBaseUri($url);
        return $provider->get('', array());
    }

    private function parseResponse($response) {

        return simplexml_load_string($response->body);
    }
}

実行

$ php app/cli.php Requestsample

成功すればRSSフィードが取得できます。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10