Re: When to instantiate a new class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Jun 28, 2015 at 4:05 AM, Larry Garfield <larry@xxxxxxxxxxxxxxxx>
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();

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux