A
A
abubekovdd2018-08-29 10:08:14
symfony
abubekovdd, 2018-08-29 10:08:14

How to do createQueryBuilder in code?

Good day!
No where in the docs can I find information on how to build an application on symfony4
. For example, I want to query a table (which has no entity) using createQueryBuilder in some arbitrary class that I created in the src folder.
How to get getDoctrine()->getManager() object to use createQueryBuilder?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2018-08-29
@abubekovdd

This should not be done in an "arbitrary" class. This must be done in the service. In which all the necessary components are transferred through dependency injection.
When configuring a service in services.yml, all the components it needs are written into the constructor arguments

foo.service:
        class: AppBundle\Helper\Foo
        arguments:
            $entityManager: "@doctrine.orm.entity_manager"

and then in the class itself in the constructor, the passed argument is assigned to the class variable
use Doctrine\ORM\EntityManager;

class Foo
{   
    /**
     * @Var EntityManager
     */
    protected $em;

    public function __construct(EntityManager $em)
    {
      $this->em = $em;
    }

The point is that Symphony should not have "arbitrary classes". All classes must fit into a clear structure. Repositories - for working with the database. Controllers process HTTP requests. "arbitrary code" is written to services. That is, it should not be just a class by itself, but a service described in the configuration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question