Php Symfony 3:如何动态操作实体?
我有一个Php Symfony 3:如何动态操作实体?,php,oop,symfony,Php,Oop,Symfony,我有一个汽车-实体,它是保险费(不是实体的一部分!),由外部提供商收取。目前,我正在将两者相互循环: 当前:(伪代码) 我想在任何地方准备/合并数据(存储库?服务?),以便能够通过汽车访问保险费: 所需:(细枝) 最好的做法是什么 提前谢谢 我假设你用条令管理你的实体 您应该为此创建一个存储库服务 use Doctrine\ORM\EntityRepository; class CarRepository extends EntityRepository { $protected $i
汽车
-实体,它是保险费
(不是实体的一部分!),由外部提供商收取。目前,我正在将两者相互循环:
当前:(伪代码)
我想在任何地方准备/合并数据(存储库?服务?),以便能够通过汽车访问保险费:
所需:(细枝)
最好的做法是什么
提前谢谢 我假设你用条令管理你的实体
您应该为此创建一个存储库服务
use Doctrine\ORM\EntityRepository;
class CarRepository extends EntityRepository
{
$protected $insuranceFeeApi;
public function setInsuranceFeeApi($insuranceFeeApi)
{
$this->insuranceFeeApi = $insuranceFeeApi;
return $this;
}
/**
* overwrite doctrine repository functions you will use to enrich your car entities with insurancefee objects
*/
public function fetchAll()
{
$insuranceFees = $this->insuranceFeeApi->getInsuranceFees(); //pseudocode
$cars = parent::fetchAll();
//enrich your car instances here
return $cars;
}
}
将此存储库设置为要用于您的car实体的存储库:
/**
* @Entity(repositoryClass="CarRepository")
*/
class Car
{
// ...
}
将此存储库声明为服务:
insurance_fee_api:
class: My\InsuranceFee\Api
car_repository:
class: Doctrine\ORM\EntityRepository
factory_service: doctrine.orm.default_entity_manager
factory_method: getRepository
arguments:
- My\Entity\Car
calls:
- ['setInsuranceFeeApi', ['@insurance_fee_api']]
使用控制器中的此存储库获取您的汽车实例:
$carRepository = $this->get('car_repository');
$cars = $carRepository->fetchAll(); // cars with insurancefees
现在,您可以将这些汽车实例传递到视图模板,并根据需要访问insurancefees
这种方法的缺点:
- 您不能对CarRepository的依赖项使用构造函数注入
- 您可能无法使用
$this->getdoctor()->getRepository()
获取存储库。相反,您必须通过容器获取存储库
您应该始终在控制器、服务、存储库、工厂等之间分离逻辑。控制器不应该做太多工作。存储库应该只处理数据库的事情。工厂应用于数据/模型映射。服务应该充分利用逻辑。“瘦控制器,胖服务”。听起来您在这里处理数据,所以映射到工厂类。就是这样做的。
insurance_fee_api:
class: My\InsuranceFee\Api
car_repository:
class: Doctrine\ORM\EntityRepository
factory_service: doctrine.orm.default_entity_manager
factory_method: getRepository
arguments:
- My\Entity\Car
calls:
- ['setInsuranceFeeApi', ['@insurance_fee_api']]
$carRepository = $this->get('car_repository');
$cars = $carRepository->fetchAll(); // cars with insurancefees