If you want to avoid instantiating a class manually everytime you need it, you can create a factory class to do it for you behind the scene and return an instance for you to use. This method doesn't give you a chance to set constructor parameters dynamically if the class needs 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\Model\Notification\Notification
factory: [Application\BackendBundle\Factory\NotificationFactory, 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\Notification;

class DefaultController extends Controller
{
private $notification;

public function __construct(Notification $notification) {
$this->notification = $notification;
}

public function indexAction()
{
var_dump($this->notification);
$this->notification->setTitle('Say');
echo $this->notification->getTitle();
exit;
}
}

Result


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

Say (hello - world)