在Symfony2中,如何在工厂类中使用服务?
我正在尝试为Chargify设置这个PHP库的Symfony实现 我有点不知所措,想不出最好/正确的方法来安排一切 我想我需要将Guzzle设置为服务,然后创建一个Chargify工厂,并将其作为服务添加 我的问题是,在factory类中,当我尝试使用Guzzle服务时,会出现致命错误在Symfony2中,如何在工厂类中使用服务?,symfony,service,factory,guzzle,chargify,Symfony,Service,Factory,Guzzle,Chargify,我正在尝试为Chargify设置这个PHP库的Symfony实现 我有点不知所措,想不出最好/正确的方法来安排一切 我想我需要将Guzzle设置为服务,然后创建一个Chargify工厂,并将其作为服务添加 我的问题是,在factory类中,当我尝试使用Guzzle服务时,会出现致命错误 Fatal error: Using $this when not in object context in /symfony/src/Acme/ChargifyBundle/Factory/ChargifyFa
Fatal error: Using $this when not in object context in /symfony/src/Acme/ChargifyBundle/Factory/ChargifyFactory.php on line 8
这是我的工厂班
<?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.");
}
}
}
我如何在工厂使用guzzle客户端而不使用
$client = $this->get('chargify.guzzle.client');
编辑:
我已经按照@alex的答案更改了代码,但仍然收到一个错误。我认为这是因为函数是静态的。我已经看过了文档,但是我看不出在没有静态函数的情况下在哪里可以设置工厂,当我去掉静态函数时,我会得到一个不同的错误
Runtime Notice: Non-static method Acme\ChargifyBundle\Factory\ChargifyFactory::build() should not be called statically, assuming $this from incompatible context
这是从一些生成的代码中抛出的
protected function getChargify_CustomerService()
{
return $this->services['chargify.customer'] = \Acme\ChargifyBundle\Factory\ChargifyFactory::build('customer');
}
让你的工厂成为一种服务,并将你的客户注入其中。从构建函数中删除static。这里都有记录:谢谢。当我删除static时,我得到了另一个错误,我看不出文档中涉及工厂的非静态函数。我有什么遗漏吗?事实上,别担心回答这个问题。我已经决定problwm实际上是我的设计,我不应该在这里使用工厂,因为每个chargify控制器都有自己的类。因此,工厂是一个不必要的复杂因素。
protected function getChargify_CustomerService()
{
return $this->services['chargify.customer'] = \Acme\ChargifyBundle\Factory\ChargifyFactory::build('customer');
}