脚本宝典收集整理的这篇文章主要介绍了php – 当你不知道它的父对象是否存在时,如何保存对象?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Business: id name Office: id name business_id Employee: id name office_id
员工将office_id作为外键,办公室将business_id作为外键.
我有一个与每个相关的域对象/实体和与每个相关的数据库映射器对象.
现在,当我由公司名称,办公室名称和员工姓名提供时,如何插入新的员工?
最初我认为逻辑应该是这样的:
$businessMapPEr = new businessMapper(); $business = $businessMapper->findBusinessByName($business_name); if ($business == false) { $business = new businessEntITy(array( 'businessName' => $business_name,)); $businessMapper->save($business); } $officeMapper = new officeMapper(); $office = $officeMapper->getOfficeByName($office_name,$business); .......etc.......
但后来我才意识到,如果我必须保存一项新业务,我就无法拥有办公室或员工,因此尝试获取它们是一种浪费的查询.那么我想我应该创建一个if / else结构.
get business entity by business_name if ($business == false) { create business entity save business entity create office entity save office entity create employee entity save employee entity } else { get office entity by office_name + business_id if (office == false) { create office entity save office entity create employee entity save employee entity } else { ......etc...... } }
但是有太多重复的逻辑,它是非常不可扩展/脏的.
那应该怎么做呢?
其次逻辑应该去哪里?它应该放在员工的映射器中吗?或“添加员工”操作的控制器还是应该有新模型?
我使用Zend作为我的框架,但我认为这个问题适用于所有MVC样式结构,所以无论您的框架偏好如何,请随时回复:)
$businessMapper = Factory::getMapper('business'); if (!$business = $businessMapper->findByName("Business Name")) { $business = $businessMapper->create(); $business->setName("Business Name"); $businessMapper->save($business); $newBusiness = true; } $officeMapper = Factory::getMapper('office'); if (isset($newBusiness) || !$office = $officeMapper->findByName("Office Name")) { $office = $officeMapper->create(); $office->setName("Office Name"); $office->setBusiness($business->getId()); $officeMapper->save($office); $newOffice = true; } $employeeMapper = Factory::getMapper('employee'); if (isset($newOffice) || !$employee = $employeeMapper->findByName("Employee")) { $employee = $employeeMapper->create(); $employee->setName("Employee Name"); $employee->setOffice($office->getId()); $employeeMapper->save($employee); }
以上是脚本宝典为你收集整理的php – 当你不知道它的父对象是否存在时,如何保存对象?全部内容,希望文章能够帮你解决php – 当你不知道它的父对象是否存在时,如何保存对象?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。