We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

DI is not recognizing $config as an object?

Hello,

My services.php looks like this:

/**

  • Setting up the view component */ $di->set('view', function(){ $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); return $view; });

    but when I run an application, i keep getting the notice : Trying to get property of non-object in /app/config/services.php on line 44

    Line 44 is: $view->setViewsDir($config->application->viewsDir)

    So apparently $config is not set-up as an object.

    Higher up, I do have /**

  • Register the global configuration as config */ $di->set('config', $config);

and it is working flawlessly with other DI members, such as the database.

Am I overlooking something or is this standard behaviour?

Thanks! Alex



12.6k
Accepted
answer
edited Nov '14

So I am assuming you're defining the $config object outside of that anonymous function? Like so:

$config = whatever;

/** * Setting up the view component */ 
$di->set('view', function(){ 
    $view = new \Phalcon\Mvc\View(); 
    $view->setViewsDir($config->application->viewsDir); 
    return $view; 
});

If so, then yes, you're simply overlooking something. $config is not in scope within the anonymous function, so you need to do this:

$config = whatever;

/** * Setting up the view component */ 
$di->set('view', function() use ($config){ 
    $view = new \Phalcon\Mvc\View(); 
    $view->setViewsDir($config->application->viewsDir); 
    return $view; 
});

Note my addition of use ($config), which adds that variable into scope for the anonymous function. There is nothing that magically converts $config into a call to the config object stored in your DI, so you need to explicitly pass that into the anonymous function as I demonstrated.



5.7k

Brilliant in its simplicity, thanks a million! Alex



12.6k

Any time :)