Asked  7 Months ago    Answers:  5   Viewed   31 times

How to use entity as service in doctrine (Using Symfony 2.1).

Example usage:

<?php

namespace MyNamespace;

class MyEntity
{
  protected $container = NULL;
  public function __construct($container)
  {
    $this->container = $container;
  }

  /** 
   * @ORMPrePersist
   */
  public function() 
  {
    // Must call to container and get any parameters
    // for defaults sets entity parameters
    $this->container->get('service.name');
  }
}

As a result, I need to get access to the entire container.

 Answers

41

An entity is a data model and should only hold data (and not have any dependencies on services). If you want to modify your model in case of a certain event (PrePersist in your case) you should look into making a Doctrine listener for that. You can inject the container when defining the listener:

services:
    my.listener:
        class: AcmeSearchBundleListenerYourListener
        arguments: [@your_service_dependency_or_the_container_here]
        tags:
            - { name: doctrine.event_listener, event: prePersist }
Wednesday, March 31, 2021
 
penpen
answered 7 Months ago
94

It appears to be an error when upgrading to Monolog Bundle 2.5.0 that causes this if you do not have the 'spool' config value set under the swiftmailer configuration.

Wednesday, March 31, 2021
 
kwhohasamullet
answered 7 Months ago
22

The parent entity needs to give visibility of it's properties to it's children.

Change your $id property visibility to "protected".

Saturday, May 29, 2021
 
Kenny
answered 5 Months ago
96

You can modify your entity where you are returning your value. In your function getM01Ch() do something like this

/**
 * @return DateTime
 */
public function getM01Ch()
{
    $returnValue = $this->m_01_ch->format('h:i:s') 
    return $returnValue
}

Other than that I don't know if any better approach exists. More info

Saturday, May 29, 2021
 
van_folmert
answered 5 Months ago
76

Don't complicate your life, you can just do

$food->getFoodGroup()->getId()

This WILL NOT perform any additional query or trigger lazy load!

Why? Because your $food->foodGroup is a proxy object which knows about it's ID. It will only do lazy load if you call a getter method of some field which hasn't been loaded.

Wednesday, July 28, 2021
 
weegee
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :