1
function app($key = null, $value = null)
{
    if (null !== $key && null !== $value) {
        $GLOBALS['__app'][$key] = $value;
    }

    return (object) $GLOBALS['__app'];
}

So, I usually have a function like this and I store things like the Request and Session objects to use them anywhere in my application. For example:

app('req', new Request);

and then I use it like this:

app()->req->getMethod();

My question is, what exactly is this? Does this function act as a Service Locator and/or Service Container? I'm trying to document my code and I'm having trouble explaining this code.

Rick
  • 11
  • 1

2 Answers2

0

It's just a hash map that creates global (app) variables. It's cast into an object so you can access its values with app()->req instead of $map = app(); $value = $map['req']

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • 1
    what makes it a service locator? – DarthVader Sep 17 '12 at 17:20
  • @DarthVader I'm not sure, but this isn't one, it's just a global map that you can put anything in it. You could use it as a service locator if you wanted, but if so, it's poorly designed because you can use it just to create global variables. – Ruan Mendes Sep 17 '12 at 17:22
  • But it is a Service Container, then? I'm not sure I understand the difference between Container and Locator. – Rick Sep 17 '12 at 17:33
  • container `DI containers` deals with creating, disposing objects, lifetime of an object. locator is just a table, map to look up for objects . it doesnt do anything about creating instances. – DarthVader Sep 17 '12 at 17:34
0

It is a service container, you can find more information here:

It's better than singleton because you can inject mocked objects, so it's much more unit testable

Community
  • 1
  • 1
dynamic
  • 46,985
  • 55
  • 154
  • 231
  • service container ? the container deals with lifetime of an object. in this case, there is no life time etc. this is straight a service locator, or registry or table. u name it. – DarthVader Sep 17 '12 at 17:33
  • The links you provided call it both Service Container AND Locator, and I'm not sure I understand the difference, if there is one! – Rick Sep 17 '12 at 17:34