Lajdák Marek Lajdák Marek - 19 days ago 7
PHP Question

Symfony 3 - menu without bundle

I have big static main menu with only 3 items which I need load from database. These items have own children so they are in multidimensional array and each item need own select so 3x select = 3x multi array.

I think I don't need any bundles because select this items is fast and easy. (+ it is project with non-standard db structure so implement bundle could be harder)

But I am new in Symfony so my question is how can I load menu items from db on one place and after this send they to view? I don't want load this items in every controller/method.

I am already tried make twig extension but after get this array i need iterate it and build html string in php class... I think it's a very bad idea...

Answer

Twig Extension is the right way to go here. But you don't have to build html string in PHP (which indeed would be wrong). You can render a Twig template inside the extension class.

Example code:

<?php
namespace AppBundle\Twig;

class MenuExtension extends \Twig_Extension
{

    public function __construct() //suitable dependecies here - probably Doctrine
    {
         //assign params to class properties
    }

    public function getName()
    {
        return 'menu_extension';
    }

    public function getFunctions()
    {
       return [
           new \Twig_SimpleFunction('menuRenderer', [$this, 'menuRenderer'], [
               'needs_environment' => true,
               'is_safe' => ['html']
           ])
       ];
    }

    public function menuRenderer(\Twig_Environment $environment)
    {
          //do all the work to get data from DB

          return $environment->render('AppBundle:Menu:main-menu.html.twig', array(
                //pass data to template
          ));
    }
}