Controlling The Flow

We now want to show a list of products in our inventory in the frontend. The component responsible for rendering that list is the view. The default view and templating engine in Extbase is Fluid.

The connection between the model and the view is the controller. The controller is responsible for fetching the data from the model and handing it to the view to be rendered. The controller uses *Action methods as entry points. In our case we want to display a list of products, so we should implement a listAction.

The class name of the controller must end with Controller. Because our controller controls the display of the inventory we call it \MyVendor\StoreInventory\Controller\StoreInventoryController.

In our simple example the controller looks like this:

<?php

namespace MyVendor\StoreInventory\Controller;

use MyVendor\StoreInventory\Domain\Repository\ProductRepository;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class StoreInventoryController extends ActionController
{
    private $productRepository;

    /**
     * Inject the product repository
     *
     * @param \MyVendor\StoreInventory\Domain\Repository\ProductRepository $productRepository
     */
    public function injectProductRepository(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function listAction()
    {
        $products = $this->productRepository->findAll();
        $this->view->assign('products', $products);
    }
}

Our \MyVendor\StoreInventory\Controller\StoreInventoryController is derived from \TYPO3\CMS\Extbase\Mvc\Controller\ActionController. It only contains the method listAction(). Extbase identifies all methods ending with Action as actions - entry points to our application.

The method injectProductRepository() shows how dependency injection looks like in Extbase - Extbase automatically injects the product repository via this method. Afterwards, we can access the repository with $this->productRepository in all actions. Use dependency injection for getting all your class dependencies if possible.

As we want to display a list of all products in our inventory, we can use the method findAll() of the repository to fetch them. findAll() is implemented in class \TYPO3\CMS\Extbase\Persistence\Repository, the parent class of our repository.

The repository returns a \TYPO3\CMS\Extbase\Persistence\Generic\QueryResult object with all product objects (that are not hidden or deleted). We pass these objects to the view with $this->view->assign(…). The view will automatically call render() and return the rendered template.

return $this->view->render();