If you want to create an instantiate of a class through a factory pattern, you can follow example below. This example gives you a chance to set constructor parameters if the class has it.


Notification class


namespace Application\BackendBundle\Model\Notification;

class Notification
{
private $param1;
private $param2;
private $title;

public function __construct($param1, $param2)
{
$this->param1 = $param1;
$this->param2 = $param2;
}

public function setTitle($title)
{
$this->title = $title . ' (' . $this->param1 . ' - ' . $this->param2 . ')';
}

public function getTitle()
{
return $this->title;
}
}

Notification factory


namespace Application\BackendBundle\Factory;

use Application\BackendBundle\Model\Notification\Notification;

class NotificationFactory
{
public static function createNotification($param1, $param2 = 'world')
{
$notification = new Notification($param1, $param2);

return $notification;
}
}

Factories.yml


services:
application_backend.factory.notification:
class: Application\BackendBundle\Factory\NotificationFactory

application_backend.class.notification:
class: Application\BackendBundle\Model\Notification\Notification
factory: [@application_backend.factory.notification, createNotification]
arguments:
- hello

Controllers.yml


services:
application_frontend.controller.default:
class: Application\FrontendBundle\Controller\DefaultController
arguments:
- @application_backend.factory.notification

DefaultController.php


namespace Application\FrontendBundle\Controller;

use Application\BackendBundle\Model\Notification\NotificationFactory;

class DefaultController extends Controller
{
private $notificationFactory;

public function __construct(NotificationFactory $notificationFactory) {
$this->notificationFactory = $notificationFactory;
}

public function indexAction()
{
var_dump($this->notificationFactory);
$notification = $this->notificationFactory->createNotification('hello', 'world');
var_dump($notification);
$notification->setTitle('Say');
echo $notification->getTitle();
exit;
}
}

Result


object(Application\BackendBundle\Factory\NotificationFactory)[648]
object(Application\BackendBundle\Model\Notification\Notification)[711]
private 'param1' => string 'hello' (length=5)
private 'param2' => string 'world' (length=5)
private 'title' => null

Say (hello - world)