Global Variables in Twig with Silex

Recently I assigned my user object to a template in my UserController. The moment I did this i realised I should assign this globally instead of reassigning it to each view. In my set-up, all my Controllers extend my CoreController class. It’s a place where I just put up some proxies that do a lot of general stuff so that my UserController (or other controllers) won’t be cluttered.

I’ve added my silex-base git repository to github, feel free to give me feedback on how my project structure looks. This repository can be installed using Composer and gives you the basic stuff you’ll need in an application. It used the Symfony Security component for registering and logging users in. Plus bonus points for twitter bootstrap.

I’ve added the filters class from my previous post (Extending Twig template engine with Silex) and a mysql dump for users and logging.  The project structure looks like this and links to the Github repository:

Silex-base Structure

Now, back to the global variable issue|bug|feature:
Because of my CoreController which has methods like getTwig() and getUser() I could easily do something like this:

    /**
     * @return \Twig_Environment
     */
    protected function getTwig() {
        // add globals
        $this->app['twig']->addGlobal('user', $this->getUser());
        return $this->app['twig'];
    }

    /**
     * @return User|Null|string
     */
    protected function getUser() {
        if(is_null($this->getSecurity()->getToken())) {
            return null;
        }

        return $this->getSecurity()->getToken()->getUser();
    }

    /**
     * @return SecurityContext
     */
    protected function getSecurity() {
        return $this->app['security'];
    }

Great, I can now use my $user object in any template. Next up is getting phpunit working within Silex.
Any hints and tips on my project structure are greatly appreciated.

2 thoughts on “Global Variables in Twig with Silex

  1. As far as structure is concerned I’d rather work with the kind where you put your User/Account/Event/AnyEntity folder directly under src/ and than have the same subfolder structure for each entity. For example:

    src/
        User/
            Controller/
                UserController.php            
            Entity/
                User.php
                UserProvider.php
            Layout/
                Profile.html
    
    1. I like the fact that all my controllers are in the same place. But I understand that it will get cluttered with 20+ controllers. What if you have a User entity and a Preferences entity. In this stage Preferences is only available for Users. Would you put Preferences in the User entity subfolder or create a new one?

Leave a reply to vanbosse Cancel reply