We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

[ solved ] Accessing DI services from Volt template

Hi all,

I'm trying to access a service I have set in my DI, from my Volt template, but I keep getting the "Undefined variable" error. I am able to access other services from the template, just not this particular one. Below is part of my bootstrap file:

    # Load config
    $Config = require '../app/config/config.php';

    # Set up the View component
    $DI->set('view',function() use($Config){
        $View = new \Phalcon\Mvc\View();
        $View->registerEngines(['.phtml'=> function($View,$DI) use ($Config){
                                            $Volt = new \Phalcon\Mvc\View\Engine\Volt($View,$DI);
                                            return $Volt;
        return $View;

    # Check authorization
    $Auth = new Auth($DI);

From my template, I am able to access Config like:

{{ Config.dir.app_dir_web }}

just not "User".

UPDATE: Reviewing my controller code I see I'm manually setting the Config variable, so it's not automagically accessible. In the documentation section about injecting services into Volt, it says "If a service container (DI) is available for Volt". What does that mean? Do I need to do anything in particular to make the my DI available to Volt?

Perhaps the error lies in the fact that you have

if ($Auth->authorize()) {

Under that if statement is where you set the shared service. If that condition is not satisfied then the service is not going to be available in the DI container.

Just a thought

I'd thought that too, but if that condition isn't met, then the else clause is entered, which shows the "not allowed" page. So, if I'm seeing the page I'm supposed to, then that condition was satisfied.

I've never used anonymous functions before so forgive me if this is completely naive, but could the problem be related to the fact that I set up my view and pass it $DI before I add the user to the DI?

edited Oct '14

Not a problem - we all learn on a daily basis :)

Try this:

# Check authorization
  $Auth = new Auth($DI);
        function () use ($Auth) {
            return $Auth->getUser();

Oh brother.... I was setting the service as "user", but trying to access it as "User". This whole thing was simply a result of me using the wrong variable name. I'll go hang my head in shame now....

Thanks for the help by the way.

P.S. Thanks to whoever updated Phosphorum to redirect me back to the current thread after logging in, rather than sending me back to the homepage.