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

Regarding di get

Is get('session') same as getSession()? It'd be great if you have any reference so I can study more on this topic.



33.8k

I think getSession() is the magic method for get("session").



25.7k

Thanks for your answer @RompePc. I did some research regarding PHP "magic method"; "magic methods" are the predefined function names that'd be called according to particular events. I'm confused should I understand "magic method" here in Phalcon as "identical"? I'm a skeptical person so when I see the doc that it doesn't really say they always return the same result, plus the comments may implies that they're different, I would like to make sure using either one are consistant.



33.8k

A magic method in PHP is a method that starts with a _ in his name, and you define his logic inside the class definition. For example:

public class A
{
    public $myVar;

    public function __set($name, $value)
    {
        echo "Setting '$name' to '$value'\n";
        $this->$name = $value;
    }
}

$a = new A();

// You will call behind the scenes the magic '_set' method, printing "Setting 'myVar' to 'WOLOLOLO'" and setting '$myVar' value to 'WOLOLOLO'.
$a->myVar = 'WOLOLOLO';

About Phalcon's magic methods, I haven't found nearly much, but I think they just act the same way. You also can do get["session"].

About of returning different values, you linked the docs of shared services.That are persistent services that, called the first time, will locate the service and return it; after the first time, it will return the same service always. In the first paragraph of your link:

Services can be registered as “shared” services this means that they always will act as singletons. Once the service is resolved for the first time the same instance of it is returned every time a consumer retrieve the service from the container.

@phalcon will tell us better.



25.7k

Thanks for your reply RompePC. If I understand correctly, function names of magic methods are predefined; like your example, __set is corresponding to the "set" event. The term "magic method" in Phalcon doc so far gave me an impression as "same", not like the way it is in the PHP description; you know, we do not define what should happen when a particular event is triggered. I actually var_dump the result of both get('session') and getSession() for non-shared service (a very brief test), they do look identical, however I'm not totally sure about it.



33.8k
edited Jan '15

Yeah, they are predefined. Maybe Phalcon's magic method just differences in the name (it creates a method with $name), not sure.

A service is differenced from a shared service that the second is persistent, not like the first, which is created in every request (likely constant vs no-constant).