从实体类获取子数据的问题(通过SESSION)



我刚从条令/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();
[...]
}
}

问题

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

我没有得到折扣(错误(,但问题是我想已经在定价级别上了。参见DUMPs:

Course.php on line 68:
Proxies__CG__AppEntityPricing {#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__AppEntityPricing {#948 ▼
+__isInitialized__: false
-id: 456
-name: null
-createdAt: null
-updatedAt: null
-courses: null
-discounts: null
…2
}

问题

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

非常感谢您的想法!!!

没关系,实体Pricing转储为未初始化。它在惰性负载下工作,所以当你调用任何定价方法时,它都会正常工作。

关于您的问题:

  1. 我认为最好将计算折扣价格的方法放在定价实体中。仅仅因为折扣仍然与定价有关,而不是与课程有关
  2. 正如我所说,尝试转储定价实体的任何获取方法,甚至折扣获取方法。它会起作用的

通过SESSION传递的对象似乎已经"死了",因此Lazy Loading不再工作。

对象首先需要"重新设置动画"。在这种懒惰加载再次工作之后:

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();
[...]
}
}

最新更新