1

I'm trying to use the Omnipay API with the Pin gateway but having issues.

I've run composer.phar locally with this in the composer.json file:

   {
    "require": {
        "omnipay/omnipay": "~2.0"
    }
    }

The composer "vendor" folder now resides at "classes/libs/vendor" on my site.

I have this payment class:

class Payment extends BasicClass {
    public function charge() {
        require "libs/vendor/autoload.php";

        use Omnipay\Omnipay;

        $gateway = GatewayFactory::create('Pin');
        $gateway->setSecretKey($this->config->secretKey);
    }
}

When calling:

$topup = new Payment();
$topup->charge();

I get a parse error, PHP takes issue with my use Omnipay\Omnipay line.

Very confused as all Omnipay documentation seems to use this syntax.

I've tried the require and use lines outside the class, but that did not help.

Thanks for everyone's help.

2 Answers2

2

You have to use the use operator outside the class definition.

From PHP documentation :

Scoping rules for importing

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.

http://php.net/manual/en/language.namespaces.importing.php#language.namespaces.importing.scope

Matthew
  • 10,988
  • 11
  • 54
  • 69
  • Thanks Matthew! Problem solved by putting `require "libs/vendor/autoload.php"; use Omnipay\Common\GatewayFactory;` at the top of my payment class file. – user2036607 Nov 27 '13 at 00:02
2

You are misusing the Composer autoloader. You are supposed to include the autoloader as one of the very first files in every request, possibly before loading any configuration files, or starting a session.

As it is currently coded, you would add another instance of the Composer autoloader whenever you make a call to that charge method. Calling charge three times in one request (for example when billing three customers in a loop) will add three autoloaders on top of each other. This sounds like a bad idea.

Please refer to the documentation at http://getcomposer.org/doc/01-basic-usage.md#autoloading to see how the composer autoloader should be included.

Especially pay attention to the paragraph stating that Composer could also autoload your own classes if you define it in your composer.json file. This is really a nice feature, you'd never again need to require the classes you are about to use.

Sven
  • 69,403
  • 10
  • 107
  • 109