mike
mike

Reputation: 1673

In Symfony2 how can I use a Service within a Factory class?

I am trying to setup a Symfony implementation of this PHP library for Chargify https://github.com/johannez/chargify

I'm getting a bit lost working out the best / proper way to set it all up.

I think I need to setup Guzzle as a service, then create a Chargify factory and have that added as a service.

My problem is that in the factory class, when I try and use the Guzzle service I get a fatal error

Fatal error: Using $this when not in object context in /symfony/src/Acme/ChargifyBundle/Factory/ChargifyFactory.php on line 8

This is my Factory class

<?php
namespace Acme\ChargifyBundle\Factory;

class ChargifyFactory implements ChargifyFactoryInterface
{
    public static function build($type)
    {
        $client = $this->get('chargify.guzzle.client');

        $className = 'Chargify\\Controller\\' . ucfirst($type);

        if (class_exists($className)) {
            return new $className($client);
        }
        else {
            throw new Exception("Invalid controller type given.");
        }
    }
}

If it's useful to see some config, this is my services.yml for the bundle

services:
    chargify.guzzle.client.curl_auth:
        class: %guzzle.plugin.curl_auth.class%
        arguments:
            api_key: %chargify_api_key%
    chargify.guzzle.client:
        class: %guzzle.client.class%
        tags:
            - { name: guzzle.client }
        calls:
            - [setBaseUrl, [%chargify_domain%]]
            - [addSubscriber, [@chargify.guzzle.client.curl_auth]]
        argument: %chargify_domain%
    chargify.factory:
        class: Acme\ChargifyBundle\Factory\ChargifyFactory
        arguments:
            - ["type"]
    chargify.customer:
        class: Acme\ChargifyBundle\Controller\CustomerController
        factory_class: Acme\ChargifyBundle\Factory\ChargifyFactory
        factory_method: build
        arguments:
            type: "customer"

How can I use the guzzle client in the Factory with out using

$client = $this->get('chargify.guzzle.client');

EDIT:

I have changed the code as per @alex's answer, but I'm still getting an error. I think this is because the function is static. I've looked though the documents, but I can't see where I can setup a factory without a static function, and when I get rid of static I get a different error.

Runtime Notice: Non-static method Acme\ChargifyBundle\Factory\ChargifyFactory::build() should not be called statically, assuming $this from incompatible context

That is being thrown from some generated code

protected function getChargify_CustomerService()
{
    return $this->services['chargify.customer'] = \Acme\ChargifyBundle\Factory\ChargifyFactory::build('customer');
}

Upvotes: 0

Views: 1308

Answers (0)

Related Questions