Search code examples
phpslimslim-3

how to set a property in Slim 3


I am trying to add a property in Slim 3 container, but when I var dump it shows me "Notice: Undefined property: Slim\App::$user". I know in Slim 2 it is:

$app->container->set('user',function(){
    return new User;
});

var_dump($app->user);

This will then show me all property in the user model container. However I am trying to achieve this in Slim 3.

I looked around the documents and found an add function but it returns an undefined property.

This is the code I tried:

$app->add('user',function(){
    return new User;
});
var_dump($app->user);

I know the User class does exist because I have tested that. I am stuck at this point and I am not sure what the method is to add a property to my container.


Solution

  • Its doesn't automatically add it as property when you register it on the DI container, you can just add it as a property with:

    $app->user = new User;
    

    Or with DI

    $app->user = $app->container->get('user');