从实体 class 获取子数据时出现问题(通过 SESSION)

Problems to get the child data from entity class (via SESSION)

我刚开始使用 doctrine / symfony,我面临以下问题:

背景

我有 3 个实体:

  1. 课程
  2. 定价
  3. 折扣

每门课程都与定价有关。定价可用于多个课程。 每个定价都有不同的折扣(以预订日期为准)。

我做了什么:

我在课程实体中添加了一个函数来获取当前价格

class Course {
   // Remark: I will skip the doctine annontation in this example
   
   // properties corresponding to database
   private $name
   private $basicprice
   [...]

   // getters and setters for the properties
   [...]

   // getter to related entities
   public function getPricing() {...}

   // additional functions
   public function getCurrentPrice() {
      dump($this->getPricing());
      dump($this->getPricing()->getName());
      dump($this->getPricing());

      $discounts = $this->getPricing()->getDiscounts(); // <-- BIG ERROR

      // +++ do some magic logic +++
      $currentDiscount = magic();
      $currentPrice    = $this->getBasicPrice() - $currentDiscount; 
     
      return $currentPrice;
   }
}

我想要的:

课程对象存储在 SESSION 中,现在应进行处理

class BookingController extends AbstractController {
   [...]
   
   public function index() {
      $session = new Session();
      $course  = $session->get('course')
      $price   = $course->getCurrentPrice();
      [...]
   }
}

问题

虽然我可以通过其他控制器获得 PRICING 和 DISCOUNTS,但我认为问题出在 SESSION 的使用上。

我没有得到折扣(错误),但问题是我猜已经在定价级别上了。查看 DUMP:

Course.php on line 68:
Proxies\__CG__\App\Entity\Pricing {#948 ▼
  +__isInitialized__: false
  -id: 456
  -name: null
  -createdAt: null
  -updatedAt: null
  -courses: null
  -discounts: null
   …2
}

Course.php on line 69:
null

Course.php on line 70:
Proxies\__CG__\App\Entity\Pricing {#948 ▼
  +__isInitialized__: false
  -id: 456
  -name: null
  -createdAt: null
  -updatedAt: null
  -courses: null
  -discounts: null
   …2
}

问题

  1. 课程中的附加功能-Class是否正确放置?还是需要进入Course-Class的子类?
  2. 为什么我没有在定价级别上获得想要的数据?

非常感谢您的想法!!!

没关系,该实体 Pricing 转储为未初始化。它适用于延迟加载,因此当您调用任何定价方法时它都会正常工作。

关于您的问题:

  1. 我认为将计算折扣价格的方法直接放入定价实体中会更好。仅仅因为折扣仍然是关于定价,而不是关于课程;
  2. 如我所说,尝试转储定价实体的任何获取方法甚至折扣获取方法。会成功的。

似乎通过 SESSION 传递的对象是 'dead',因此延迟加载不再起作用。

对象首先需要是 're-animated'。在此延迟加载再次工作后:

class BookingController extends AbstractController {
   [...]
   
   public function index() {
      $session   = new Session();
      $course    = $session->get('course')
      $course_id = $course->getId();
      $course    = $this->courseReository->find($course_id);
      $price     = $course->getCurrentPrice();
      [...]
   }
}