How do I use Doctrine in a service container?
The Code just causes an error message "Fatal error: Call to undefined method ...::get()".
<?php namespace ...\Service; use Doctrine\ORM\EntityManager; use ...\Entity\Header; class dsdsf { protected $em; public function __construct(EntityManager $em) { $this->em = $em; } public function create() { $id = 10; $em = $this->get('doctrine')->getEntityManager(); $em->getRepository('...')->find($id); } }
services.yml
service: site: class: ...\Service\Site
Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB.
In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!
With the doctrine:database:create command we create a new database from the provided URL. With the make entity command, we create a new entity called City . The command creates two files: src/Entity/City. php and src/Repository/CityRepository.
According to your code, you already have an EntityManager
injected. You don't need to call $em = $this->get('doctrine')->getEntityManager()
— just use $this->em
.
If you don't inject an EntityManager
already, read this.
UPDATE:
You need to make the container inject an EntityManager
into your service. Here's an example of doing it in config.yml
:
services: your.service: class: YourVendor\YourBundle\Service\YourService arguments: [ @doctrine.orm.entity_manager ]
I prefer to define bundles' services in their own services.yml
files, but that's a bit more advanced, so using config.yml
is good enough to get started.
For easily accessing the Entitymanager use the following one:
//services.yml your service here: class: yourclasshere arguments: [@doctrine.orm.entity_manager]
And in the class itself:
class foo { protected $em; public function __construct(\Doctrine\ORM\EntityManager $em) { $this->em = $em; } public function bar() { //Do the Database stuff $query = $this->em->createQueryBuilder(); //Your Query goes here $result = $query->getResult(); } }
This is my first answer so any comments are appreciated :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With