title: Best practice to implement Factory pattern using Symfony2
body: <p>I am making a messenger which can send email messages or sms messages, and has the possibility to send them now or send them later (the information is saved in the DB). I've made 2 solutions, but neither is satisfying me. </p>
  
  <p>I'm centralising the code in one Factory, and the code of the Factory pattern is very easy:</p>
  
  <pre><code>class MessageFactory
  {
       static public function get($type,$em)
       {
            $instance = null;
            switch ($type) {
                case 'email':
                      $instance = new EmailMessage($em);
                      break;
     ....
    return $instance;
  }
  
  class EmailMessage implements MessangerInterface
  {
   ...
     public function send( $eMessage,array $receivers, $time=NULL)
     {
  
  interface MessangerInterface
  {
    public function send($message,array $receivers);
  }
  </code></pre>
  
  <p><strong>1st solution:</strong> Just call as an ordinary static method</p>
  
  <pre><code>$messanger = Factory\MessageFactory::get('email',$em);
  $messanger-&gt;send($eMessage, array('tom'=&gt;'tom@gmail.com'));
  </code></pre>
  
  <p>This is a bad solution, because I need to pass in a Doctrine Manager as a parameter to the method</p>
  
  <p><strong>2nd solution:</strong> To use it as a Symfony 2 Service</p>
  
  <pre><code>services:
  my.messanger:
      class: Bundle\Factory\MessangerInterface
      factory_class: Bundle\Factory\MessageFactory
      factory_method: get
      arguments:
          messanger_type: %messanger.type%
  </code></pre>
  
  <p>and also pass in Doctrine as an argument.  But using such a solution I can't choose messanger.type in my code, it's defined using a configuration parameter as <code>email</code> or <code>sms</code>; I need to have the capability in code to choose the type.</p>
  
  <p>Also I have a problem that inside the class I need to send email or sms, and that means that I need an external service, getting it like this:</p>
  
  <pre><code>class EmailMessage implements MessangerInterface
  {
   if ('AppCache' == get_class($kernel)) {
        $kernel = $kernel-&gt;getKernel();
     }
   $kernel-&gt;getContainer()-&gt;get('mailer')-&gt;send($eMessage);
  </code></pre>
  
  <p>which seems like very bad practice.</p>
  
  <p>Please, are you able to advise me on any better solutions?</p>
  
  <p>I want to follow the "thin controller fat model" concept.</p>