04/08/2015 - SYMFONY
Bir classın örneğini sürekli manuel olarak yaratmak yerine, onu factory pattern niteliğinde kullanıp, otomatik olarak örneğini alabilirsiniz. Eğer class constructor ile parametre kabul ediyorsa, maalesef bu yöntem size dinamik olarak parametreleri değiştirme olanağı vermiyor.
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;
}
}
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;
}
}
services:
application_backend.factory.notification:
class: Application\BackendBundle\Model\Notification\Notification
factory: [Application\BackendBundle\Factory\NotificationFactory, createNotification]
arguments:
- hello
services:
application_frontend.controller.default:
class: Application\FrontendBundle\Controller\DefaultController
arguments:
- @application_backend.factory.notification
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;
}
}
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)