Navigation

Query Container

A query container holds all the database queries of the current module.

Each module has exactly one query container, which also acts as an entry point to the persistence layer. Internally it uses query objects and returns unterminated queries.

As you can see in the example below, the query container consists of query-methods which get query objects from the factory, add some filters or joins and return the unterminated query object.

Unterminated means you don’t execute the query with find(), findOne() or count().

use Spryker\Zed\Kernel\Persistence\AbstractQueryContainer;

/**
 * @method \Pyz\Zed\MyBundle\Persistence\MyBundlePersistenceFactory getFactory()
 */
class MyBundleQueryContainer extends AbstractQueryContainer implements MyBundleQueryContainerInterface
{
    public function queryTemplateByPath($path)
    {
        $query = $this->getFactory()->createTemplateQuery();
        $query->filterByTemplatePath($path);

        return $query;
    }
}

How to use a query container

The query container of the current unterminated query is available via $this->getQueryContainer() in the factory of the communication and the business layer and can be injected into any model.

Query container via factory

Execute the query

You can adjust the query itself, but you should avoid to add more filters or joins because this is a responsibility of the query container only.

<?php
$templateQuery = $this->queryTemplateByPath($path);
$templateQuery->limit(100);
$templateQuery->offset(10);
$templateCollection = $templateQuery->find(); // or findOne()

You can also change the output format, e.g. to array instead of collection:

<?php
$formatter = new SimpleArrayFormatter();
$templateQuery->setFormatter();

Implementing a query container

Snippet to create a new query container

To create a new query container you can copy and paste the following snippet and replace MyModule with your module name.

<?php
namespace Pyz\Zed\MyBundle\Persistence;

use Spryker\Zed\Kernel\Persistence\AbstractQueryContainer;

/**
 * @method MyBundlePersistenceFactory getFactory()
 */
class MyBundleQueryContainer extends AbstractQueryContainer implements MyBundleQueryContainerInterface
{
}

Conventions for query containers

There are some conventions which should be followed here:

  • All methods have the prefix query*().
  • All public methods are exposed in the related interface (e.g. MyBundleQueryContainerInterface).
  • Queries are returned unterminated, so that the user can add restrictions (limit, offset) and can choose how to terminate (count(), find(), findAll()).
  • Query containers do not access higher layers. So no usage of a facade here.
  • Query containers do not contain any logic which is not needed to build queries.