Quantcast
Channel: Serverphorums.com
Viewing all articles
Browse latest Browse all 23908

Re: [PHP] When to instantiate a new class

$
0
0
On Sun, Jun 28, 2015 at 4:05 AM, Larry Garfield <larry@garfieldtech.com>
wrote:

> What you describe is a service locator. Which is basically the same thing
> as a dependency injection container that you pass into the object you're
> using. Google "service locator bad" for why you shouldn't do that. :-)


"Service Locator" (according to this
http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ and this
https://en.wikipedia.org/wiki/Service_locator_pattern) seems to be when
you have a global registry mapping class names (or some other key) to some
means of instantiating that class/service. That *would* cause problems.

What I was describing was something simple like this:

<?php


class FooDeps {

/** @return IBarService */

function getBarService() {

return new DefaultBarService;

}

// ...

}


class Foo {

/** @var FooDeps */

private $deps;


function __construct(FooDeps $deps = null) {

$this->deps = $deps ?: new FooDeps;

}


function doFoo() {
$barService = $this->deps->getBarService();
// ...
}

// ...

}



// ===========


// in some other file..


// I need a Foo, but I want it to use SpecialBarService instead of

// DefaultBarService as an implementation of IBarService


// (Anonymous classes in PHP7 would be handy here)

class SpecialFooDeps extends FooDeps {

/** @return IBarService */

function getBarService() {

return new SpecialBarService;

}

}


$foo = new Foo(new SpecialFooDeps);
$foo->doFoo();

Viewing all articles
Browse latest Browse all 23908

Trending Articles