Search code examples
phplaravellaravel-4facade

Passing App object to function / class in Laravel


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()


Solution

  • 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)