I am looking to access to a variable inside a service.
The variable is an object class.
This is the services.yml
services:
project.notification:
class: NotificationsBundle\Command\ServerCommand
// this is the class
class ServerCommand extends ContainerAwareCommand {
public $notification;
/**
* Configure a new Command Line
*/
protected function configure() {
$this->setName('Project:notification:server') ->setDescription('Start the notification server.');
}
public function getNotification()
{
return $this->notification;
}
protected function execute(InputInterface $input, OutputInterface $output) {
$this->notification = new Notification();
$server = IoServer::factory(new HttpServer(
new WsServer(
$this->notification
)
), 8081);
$server->loop->addPeriodicTimer(1, function () {
$this->notification->sendToAll('Hello');
});
$server->run();
}
}
I would like to get the variable $notification from another controller.
When I do that I got an error "non-existent object" ($notification).
I run the service by executing the following command:
php app/console Project:notification:server
It has to be the current object I can not create a new one because the list of users it is inside the object $notification.
Any ideas?
Related
How can I directly create an object instance in a certain way? This object is a task handler, the processor of each task may be different. Is it similar to the method of Yii::createObject(). I don’t want to register handlers in service.yarml, because there may be many handlers.
Here is what I would like to acheive:
$task = new Task;
// $handler = $this->container->get($task->getHandlerName());
$handler = createObject($task->getHandlerName());
$handler->handle($task);
// Handler
class MyHandler {
private $manager;
// autowiring
public function __construct(EntityManagerInterface $manager) {
$this->manager = $manager;
}
public function handle() {
}
}
I am trying to simplify my applications dependency injection by creating a base injection class.
So far most of the code works fine, except for registerForAutoconfiguration
Here is the relevant code:
abstract class AbstractTaggedPass implements CompilerPassInterface
{
protected $interfaceClass;
protected $serviceClass;
protected $tag;
protected $method;
public function process(ContainerBuilder $container)
{
// always first check if the primary service is defined
if (!$container->has($this->serviceClass)) {
return;
}
// Register classes implementing the interface with tag
$container->registerForAutoconfiguration($this->interfaceClass)->addTag($this->tag); // Does not work
$definition = $container->findDefinition($this->serviceClass);
// find all service IDs with the tag
$taggedServices = $container->findTaggedServiceIds($this->tag);
foreach ($taggedServices as $id => $tags) {
foreach ($tags as $attributes) {
$definition->addMethodCall($this->method, [new Reference($id)]);
}
}
}
}
class SubscriptionPaymentProviderPass extends AbstractTaggedPass
{
protected $interfaceClass = SubscriptionPaymentProviderInterface::class
protected $serviceClass = SubscriptionPaymentProviderPool::class;
protected $tag = 'subscription.payment_provider';
protected $method = 'addProvider';
}
class SubscriptionBundle extends Bundle
{
protected function getContainerExtensionClass()
{
return SubscriptionExtension::class;
}
public function build(ContainerBuilder $container)
{
parent::build($container);
//$container->registerForAutoconfiguration(SubscriptionPaymentProviderInterface::class)->addTag('subscription.payment_provider');
$container->addCompilerPass(new SubscriptionPaymentProviderPass());
}
}
If I move registerForAutoconfiguration line from Bundle class into the CompilerPass class, then it no longer registers Services with the correct tag.
Is it possible to use it inside a compiler pass?
Do I need to enable something to make it work?
Compiler Pass is used after service definitions are parsed (via configuration file or extensions).
I think the right place for do this, is into an Extension.
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.
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)
I have created a console command page in my bundle for cronjob.
Here is the code
class MyCommand extends Command {
protected function configure()
{
$this
->setName('cron:item_email')
->setDescription('product notification for customer that reserved');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->container = $this->getApplication()->getKernel()->getContainer();
$em = $this->container->get('doctrine.odm.mongodb.document_manager');
$wishlist = $em->getRepository('xxxxBundle:Wishlist')->findAll();
foreach($wishlist as $wish){
if($wish->getReservedDate()){
// $output->writeln($wish->getId());
$output->writeln($wish->getReservedDate());
}
}
}
}
Here I am retrieving mongo db date "$wish->getReservedDate()"
But I am getting the output like this
2013-07-03 13:46:42
3
Europe/Berlin
How I get the date only for ex: 2013-07-03 13:46:42
$wish->getReservedDate()->format('d/m/Y H:i:s')
Also as a side note, the ID has the date stored in it also.
Just a FYI