I've a Car
-entity and it's insurance fees
(not part of the Entity!), which I receive by an external provider. At the moment I'm looping both against each others:
Current: (pseudocode)
foreach ($insuranceFeesArr as $insuranceFeesObj):
if ($insuranceFeesObj.carId == $car.id):
echo 'Fees: ' . $insuranceFeesObj.USD; // "Fees: 75.00 USD"
endif;
endforeach;
I'd like to prepare/merge the data anywhere (repository? service?) to be able to access the insurance fees by the Car
:
Desired: (twig)
{{ car.insuranceFees.USD }} // Fees: 75.00 USD
What's the best or a good practice?
Thanks in advance!
I assume you manage your entities with doctrine.
You should create a repository service for that purpose.
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;
}
}
Set this repository as the repository to be used for your car entity:
/**
* @Entity(repositoryClass="CarRepository")
*/
class Car
{
// ...
}
Declare this repository as a service:
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']]
Use this repository within your controller to fetch your car instances:
$carRepository = $this->get('car_repository');
$cars = $carRepository->fetchAll(); // cars with insurancefees
You may now pass these car instances to your view templates and access the insurancefees as desired.
Drawbacks with this method:
You may not use constructor-injection with the dependencies of CarRepository
You may not get the repository using $this->getDoctrine()->getRepository()
. Instead, you have to get the repository via container
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.