【问题标题】:laravel 7 including external classlaravel 7 包括外部类
【发布时间】:2020-12-31 10:01:32
【问题描述】:

我正在尝试包含一个外部类以使用 API,但出现此错误:

找不到类“App\Services\VedicRishiClient”

$vedicRishi = new VedicRishiClient($userId, $apiKey);

我遵循了这个https://laraveldaily.com/how-to-use-external-classes-and-php-files-in-laravel-controller/ 教程。

不知道该怎么办?

这是我的 PagesController

<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Profilecard;
use App\User;
use Auth;
use App\Services\VedicRishiClient;

class PagesController extends Controller
{
public function index()
{
    // instantiate VedicRishiClient class
    $vedicRishi = new VedicRishiClient($userId, $apiKey);

    $responseData = $vedicRishi->call($resourceName,$data);

    return $responseData;

    return view('pages.index')->with('location', $location);
}

这是我试图包含的附加类:

<?php

class VedicRishiClient
{
private $userId = null;
private $apiKey = null;
private $apiEndPoint = "http://api.vedicrishiastro.com/v1";

/**
 * @param $uid userId for Vedic Rishi Astro API
 * @param $key api key for Vedic Rishi Astro API access
 */
public function __construct($uid, $key)
{
    $this->userId = $uid;
    $this->apiKey = $key;
}

private function getCurlReponse($resource, array $data)
{
    $serviceUrl = $this->apiEndPoint.$resource;
    $authData = $this->userId.":".$this->apiKey;

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $serviceUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    $header[] = 'Authorization: Basic '. base64_encode($authData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

public function call($resourceName, $data)
{
    $resData = $this->getCurlReponse($resourceName, $data);

    return $resData;
}

}

【问题讨论】:

  • 请显示更多代码。您是否将您的课程添加到 App 命名空间?你没有忘记正确的use 声明吗?
  • 我添加了代码
  • 也许你应该更仔细地阅读教程。特别是关于如何在控制器中包含外部类的部分。
  • 知道了。谢谢!
  • 您的班级缺少正确的namespace 声明。

标签: php class laravel-7


【解决方案1】:

这取决于在哪里

VedicRishiClient

找到类。

显然它不在 App\Services\VedicRishiClient 的位置。默认情况下,它将在当前文件命名空间中查找(查找 php 文件的顶部)。

如果直接访问VedicRishiClient,那么试试

$vedicRishi = new \VedicRishiClient($userId, $apiKey);

相反,或添加

use VedicRishiClient;

到脚本的顶部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    相关资源
    最近更新 更多