Symfony Factory class - symfony

I would like to use a ResultFactory class as a service in my Symfony 2 application:
My Result factory class will be responsible to create a BaseResult instance.
Depending on the type passed to the get factory method, the ResultFactory will create the right ResultObject.
Here's what could be the code:
class ResultFactory
{
protected $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
public function get($type, $param)
{
$instance = null;
switch ($type) {
case 'Type1':
$instance = new Type1Result($param);
break;
case 'Type2':
$instance = new Type2Result($param);
break;
}
return $instance;
}
}
My question is:
I would like to use a service in my ResultObject. How do i inject this service to my ResultObject?
Thanks!

You are not using your service inside a result object. your factory is generating the result object.
You can define your factory service in services.yml of your bundle as:
result.factory:
class: ResultFactory
arguments: ["#translator"]
And in your controller you can call the service:
$resultObject = $this->get('result_factory')->get($type, $param);
Also you have core example how to create factory service using symfony2 in [the docs].(http://symfony.com/doc/current/components/dependency_injection/factories.html)

Related

How do I pass an id variable to a class which has dependency injection Symfony 3.4

I have class that uses Dependency Injection, with two other classes, this works fine. But I want to then instantiate the Merchant class in a controller and pass an id . Thing I don't get is the constructor is expecting more values 'CurrencyConverter' and 'TransactionTable' so how can I complete the code ? ?, which I don't need to pass. So I'm not clear how to make it work, thanks
Model Class
namespace TransactionBundle\Model;
class Merchant
{
public $_transactions;
public $_currencyConverter;
public $_id;
public function __construct($id,CurrencyConverter
$currencyConverter,TransactionTable $transactions)
{
$this->_transactions = $transactions;
$this->_currencyConverter = $currencyConverter;
$this->_id = $id;
}
public function getTransactions() {
$this->_currencyConverter->convert();
$this->_transactions->getData();
}
}
trying to instantiate in the controller
$merchant = new Merchant(2,?,?);
$results = $merchant->getTransactions();
If the class has a dependency on something that is not in the container, then the class cannot be loaded from the container.
Either pass the dependencies yourself in the controller:
$merchant = new Merchant(2, $currencyConverter, $transactions);
Or use a factory service in the container:
class MerchantFactory {
private $currencyConverter;
private $transactions;
// constructor omitted for brevity
public function getMerchantForId($id) {
return new Merchant($id, $this->currencyConverter, $this->transactions);
}
}
Then in your controller, depend on the factory:
$merchant = $this->merchantFactory->getMerchantForId(2);

Inject form factory into a service

I'm trying to create a manager to handle basic requests of a controller (list, new, edit, delete). I need to inject the form factory within the constructor of this service. By what name should I call?
I need something like this:
lp_ExpedienteManager:
class: AppBundle\Services\ExpedienteManager\ExpedienteManager
arguments: [ "#doctrine.orm.entity_manager", "#security.token_storage", "#form_factory" ]
Thanks for your time!
For future references, since Symfony 3.3 this service is available as Symfony\Component\Form\FormFactoryInterface. So you can inject in your services like
use Symfony\Component\Form\FormFactoryInterface;
class AccountBridge
{
private $formFactory;
public function __construct(FormFactoryInterface $formFactory)
{
$this->formFactory = $formFactory;
}
public function accountCreateAction(Account $account)
{
$form = $this->formFactory->create(AccountType::class, $account);
}
}

How to inject dependency using Factory Pattern in Symfony2

I have this situation
abstract class Importer {
const NW = 1;
public static function getInstance($type)
{
switch($type)
{
case(self::NW):
return new NWImporter();
break;
}
}
protected function saveObject(myObject $myObject)
{
//here I need to use doctrine to save on mongodb
}
abstract function import($nid);
}
and
class NWImporter extends Importer
{
public function import($nid)
{
//do some staff, create myObject and call the parent method to save it
parent::saveObject($myObject);
}
}
and I want to use them like this
$importer = Importer::getInstance(Importer::NW);
$importer->import($nid);
my question is: how to inject doctrine to be used in saveObject method?
thanks
You need to configure your importer as a symfony service :
services:
test.common.exporter:
# put the name space of your class
class: Test\CommonBundle\NWImporter
arguments: [ "#doctrine" ]
then in NWImporter define a constructor with a parameter that will have the doctrine instance
public function __construct($doctrine)
{
$this->doctrine= $doctrine;
}
with this solution you can avoid using a factory method as symfony does it for you but if you wanna to keep it, When you call $importer = Importer::getInstance(Importer::NW); from your controller you can inject the doctrine argument in your factory method :
abstract class Importer {
const NW = 1;
public static function getInstance($type, $doctrine)
{
switch($type)
{
case(self::NW):
return new NWImporter($doctrine);
break;
}
}
protected function saveObject(myObject $myObject)
{
//here I need to use doctrine to save on mongodb
}
abstract function import($nid);
}
then in your controller you should to do something like that :
$doctrine = $this->container->get('doctrine');
$importer = Importer::getInstance(Importer::NW, $doctrine);
$importer->import($nid);

Retrieve arguments in Service - Symfony

I want to understand service in symfony
I have read http://symfony.com/doc/2.3/book/service_container.html#creating-configuring-services-in-the-container
and I want to try to create my service
in my config.yml
services:
my_service:
class: Acme\FooBundle\myService
arguments: ['my_param']
in My controller
public function serviceAction(){
$Myservice = $this->get('my_service');
return array();
}
in My Class /service
class myService{
public function __construct() {
echo "In BaseClass constructor\n";
}
}
The Question is:
How can I Retrive my_param in my Class service?
I want to retrieve arguments: ['my_param']
Arguments are being passed to your service constructor as parameters:
class myService{
private $my_param;
public function __construct($param) {
$this->my_param = $param;
echo $this->my_param;
echo "In BaseClass constructor\n";
}
}

Singleton between different controller actions in Symfony2

Assume we have singleton class
class Registry {
private static $_instance;
private function __construct() {}
private function __wakeup() {}
private function __clone() {}
private $_map = array();
public static function getInstance () {
if (self::$_instance === null)
self::$_instance = new self();
return self::$_instance;
}
public function set ($key, $val) {
self::getInstance()->_map[$key] = $val;
return self::getInstance();
}
public function get($key)
{
if (array_key_exists($key, self::getInstance()->_map))
return self::getInstance()->_map[$key];
return null;
}
}
And we have simple Symfony2 Controller with 2 actions
class IndexController {
public function indexAction () {
Registry::getInstance()->set('key',true);
return new Response(200);
}
public function secondAction () {
$val = Registry::getInstance()->get('key');
return new Response(200);
}
}
I call index action, then second action. But I can't find key, that was set in first action. I think, new instance of singleton creates in my second action. Why object is not saved in memory? What do I do wrong?
If you call indexAction and secondAction in different requests it won't work the way you want it because your Registry instance is not shared between requests.
Singleton itself does not store anything "in memory" (BTW Singleton is now considered as an anti-pattern).
What, I think, you want to achieve can be done by using session storage. Check doc for more info how to implement this.

Resources