douwu7563 2014-09-23 06:51
浏览 138
已采纳

在Laravel中将App对象传递给函数/类[重复]

I'm working with Laravel 4.2, calling a payment flow between form submit and the controller response. If the payment is accepted, a bunch of work is done behind the scene by the class PaymentProcessor

use MyProject\libraries\payment\PaymentProcessor;

class MyFirstController extends \Controller {

    protected $paymentProcessor;

    public function __construct(
        PaymentProcessor $paymentProcessor
    ) {
        $this->paymentProcessor = $paymentProcessor;
    }

    public function postFormSubmit() {
        //DO SOME STUFF
        $paymentResult = $this->paymentProcessor->makePayment($paymentDetails);
    }
}

PaymentProcessor is on a different namespace, and I'm able to call a needed library using App::make

<?php namespace MyProject\libraries\payment;

use MyProject\DataObjects\PaymentDetails;

class PaymentProcessor {

    public function makePayment(PaymentDetails $paymentData) {
        $doFirstStep = \App::make('amazingLibrary')->doImportantThings();

but, for testing purposes I want to remove all instantiations and calls to other classes directly from PaymentProcessor, so I've tried to do the following injection:

<?php namespace MyProject\libraries\payment;

use MyProject\DataObjects\PaymentDetails;

class PaymentProcessor {
    private $app;

    public function __construct(\App $app) {
        $this->app = $app;
    }

And tried:

    public function makePayment(PaymentDetails $paymentData) {
        $doFirstStep = $this->app::make('amazingLibrary')->doImportantThings();

But it leads to:

FatalErrorException (E_PARSE) syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

Am I in the right way?

Update:

I've also tried to call it as: $this->app->make

That leads to:

Call to undefined method Illuminate\Support\Facades\App::make()

</div>
  • 写回答

1条回答 默认 最新

  • doune1000 2014-09-23 07:16
    关注

    Probably you want to do something like that:

    something($app);
    
    function something (\Illuminate\Foundation\Application  $app) {
    
        echo  $app->getLocale();
    }
    

    So in your case you need to use $this->app->make syntax and you need to pass parameter as I showed (and $app is instance of \Illuminate\Foundation\Application not \App)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低