duandian4501 2018-08-29 19:24
浏览 28

ApiCommand.php是如何在laravel中工作的?

I just wonder how ApiCommand.php works in laravel?

This is my ApiCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

use DB;

class ApiCommand extends Command {
/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'api:command';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Command description';

/**
 * Create a new command instance.
 *
 * @return void
 */
public function __construct()
{
    parent::__construct();
}

/**
 * Execute the console command.
 *
 * @return mixed
 */

public function handle()
{
    include(app_path() . '/includes/HelloAnalytics.php');
    include(app_path() . '/includes/DeepCrawl.php');  
    include(app_path() . '/includes/Uptime.php');
}

This is my HelloAnalytics.php

<?php

// Load the Google API PHP Client Library.
//require_once '/home/vagrant/apps/pc-reporting-tool/vendor/autoload.php';
include(base_path() . '/vendor/autoload.php');
$results = array();
$otherResults = array();
$analytics = initializeAnalytics();
// there are two websites in google analytics account so $i<2 is used
for($i=0;$i<2;$i++){
$profile[$i] = getFirstProfileId($analytics,$i);

//**** get the property name
$propertyName[$i] = $profile[$i][0];

/* results of a profile is saved with each iteration. The loop iterates
    until all the profile in google analytics account is save */
$results[$i] = getResults($analytics, $profile[$i][1]);
$otherResults[$i] = getOtherResults($analytics, $profile[$i][1]);
}


function initializeAnalytics(){
// Creates and returns the Analytics Reporting service object.

// Use the developers console and download your service account
$KEY_FILE_LOCATION = app_path() . '/includes/GoogleAnalytics.json';

// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);

return $analytics;
}


function getFirstProfileId($analytics,$index) {
// Get the user's first view (profile) ID.

// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();

if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();

// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
    ->listManagementWebproperties($firstAccountId);

if (count($properties->getItems()) > 0) {
  $items = $properties->getItems();
  $firstPropertyId = $items[$index]->getId();
  //*******************
   $firstPropertyName = $items[$index]->getName();

  // Get the list of views (profiles) for the authorized user.
  $profiles = $analytics->management_profiles
      ->listManagementProfiles($firstAccountId, $firstPropertyId);

  if (count($profiles->getItems()) > 0) {
    $items = $profiles->getItems();

      //***** stores Property name and Profile Id as an array
      $info = [];
      $info[0] = $firstPropertyName;
      $info[1] = $items[0]->getId();
    // Return the first view (profile) ID.
    //return $items[0]->getId();

      return $info;
        } else {
    throw new Exception('No views (profiles) found for this user.');
     }
     } else {
  throw new Exception('No properties found for this user.');
     }
  } else {
  throw new Exception('No accounts found for this user.');
    }
  }

function getResults($analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'yesterday',      
'ga:users', 
['dimensions'=>'ga:deviceCategory,ga:browser'] */
['dimensions'=>'ga:day'] 
  );
}

function getOtherResults($analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'yesterday',      
  'ga:users,ga:newUsers,ga:sessions,ga:sessionsPerUser,ga:pageviews,ga:pageviewsPerSession,ga:avgSessionDuration,ga:bounceRate'
  );
}

function printResults($results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {

// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();

// Get the entry for the first entry in the first row.
$rows = $results->getRows();


$sessions = $rows[1][0];

// Print the results.
//print "First view (profile) found: $profileName
";
//print "Total visits: $sessions
";
//print "Total users: $users
";
} else {
   print "No results found.
";
  }
}

This is my Uptime.php

<?php 

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.uptimerobot.com/v2/getMonitors",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "api_key=XXXX",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
$data = json_decode($response);
$custom_uptime = ($data->monitors[0]->custom_uptime_ratio);
$uptime = explode("-",$custom_uptime);
}

?>

DeepCrawl.php was not done yet.

My problem is I want to use ApiCommand and use that handle function to gather all the data's for my google analytics uptime and deepcrawl but I don't know how it works. Sorry for my bad grammar cause I'm not use to it and I'm just new in the programming environment. Hopefully someone can help me how ApiCommands.php works. Thanks in advance.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥120 计算机网络的新校区组网设计
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等
    • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
    • ¥15 qt6.6.3 基于百度云的语音识别 不会改
    • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
    • ¥15 神经网络怎么把隐含层变量融合到损失函数中?