Skip to content

Commit

Permalink
使用事件来处理response数据
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavle Lee committed Mar 8, 2016
1 parent 66626d0 commit b56c938
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 19 deletions.
30 changes: 11 additions & 19 deletions Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

use Curl\Curl;
use yii\base\Component;
use yii\base\ErrorException;
use yii\base\Event;
use yii\helpers\ArrayHelper;

class Connection extends Component
Expand All @@ -30,29 +30,21 @@ class Connection extends Component
*/
protected $curl;

/**
* @var callable
*/
public $success;

/**
* @var callable
*/
public $error;
const EVENT_CURL_SUCCESS = 'curlSuccess';
const EVENT_CURL_ERROR = 'curlError';

public function init()
{
parent::init();
$this->curl = new Curl();
!$this->success && $this->success = function (Curl $curl) {
$curl->response = ArrayHelper::toArray($curl->response);
};
!$this->error && $this->error = function (Curl $curl) {
\Yii::trace(serialize($curl->response), 'rest.connect');
throw new ErrorException($curl->errorMessage);
};
$this->curl->success($this->success);
$this->curl->error($this->error);
$this->curl->success(function(Curl $curl){
$event = new CurlEvent(['curl' => $curl]);
Connection::trigger('curlSuccess', $event);
});
$this->curl->error(function(Curl $curl){
$event = new CurlEvent(['curl' => $curl]);
Connection::trigger('curlError', $event);
});
}


Expand Down
16 changes: 16 additions & 0 deletions CurlEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php
/**
* User: 李鹏飞 <[email protected]>
* Date: 2016/3/8
* Time: 13:13
*/

namespace pavle\yii2\rest;


use yii\base\Event;

class CurlEvent extends Event
{
public $curl;
}

0 comments on commit b56c938

Please sign in to comment.