【问题标题】:Passing the results of an API call to the class将 API 调用的结果传递给类
【发布时间】:2015-06-24 18:06:42
【问题描述】:

我已经为我正在使用的 API 制作了自己的 Wrapper,现在我有一个可以注册用户的类,我需要在整个类中获取该 API 调用的结果。

所以我想知道是否有可能让结果对象 API 作为对象返回以使用并传递给其他方法

这是我的代码,我添加了内联 cmets 以澄清问题

class RegisterController extends Controller {

    private $company;

    public function __construct()
    {
        // This is not the object I want, It's the class that communicates with the API
        $this->company = new Teamleader\Company;
    }

    public function index($id = null)
    {
        // I'm trying to set the class to the result of the API call ( returns an StdObject )
        $this->company = $this->company->get($id);

        // Still returns the original object, not the result of the API call
        var_dump($this->company);
    }

    public function register()
    {
        // Also returns the original object
        dd($this->company);
    }

}

非常感谢你,一个困惑的开发者。

【问题讨论】:

    标签: php class laravel


    【解决方案1】:

    不要尝试覆盖 api 包装器,只需将其设置为一些自定义响应对象。

    namespace Teamleader;
    
    class CompanyResponse {
    
        protected $data = null;
    
        public function __construct(\stdClass $data)
        {
            $this->data = $data;
        }
    
        // Whatever other methods you want to be in the API response
    }
    

    然后在Teamleader\Company 中的get 方法中,您将return new CompanyResponse($data)

    RegisterControllerindex 方法中,将响应对象设置为不同的类属性。确实没有太多理由覆盖您创建的 API 包装器。

    $this->companyResponse = $this->company->get($id);
    

    【讨论】:

    • 感谢您的回答,这是处理 API 调用的好方法吗?还是我看错了,我觉得应该有更好的方法..
    • 如果您必须操作/存储/缓存 API 返回的数据,那么我会说这是一个非常好的方法。我唯一会做的不同是将你的 api 包装器注入到控制器类中。
    • 你可能有一个小例子吗?感谢您的宝贵时间!
    • 是的,你运行的是哪个版本的 Laravel?
    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多