WebDevStudios / oops-wp

A collection of abstract classes, interfaces, and traits to promote object-oriented programming practices in WordPress.
57 stars 9 forks source link

Change visibility of `init_services` method in ServiceRegistrar from private to protected. #23

Closed jmichaelward closed 5 years ago

jmichaelward commented 5 years ago

Use case:

In 0.2.0, the init_services method looks like this:

    private function init_services() {
        $objects = array_map( function ( $service_class ) {
            return [
                'namespace' => $service_class,
                'object'    => new $service_class(),
            ];
        }, $this->services );

        return array_column( $objects, 'object', 'namespace' );
    }

This accepts an indexed array of class names and returns an associative array where the key is the service's class name and the value is the instantiated Service object. Generally, this is what we want - it keeps Service object instantiation simple and eliminates any immediate need for dependencies.

That said, there may be situations where our Service classes might be more complex, and we want to pass a shared dependency into multiple Service objects. In those situations, we may want fine-tuned control over how our Service objects are created, either via use of a dependency injection conatiner such as Auryn, or some other method. In those cases, we'll need to override this method, which is not currently possible due to its private visibility. An example override might look like this:

    protected function init_services() {
        $objects = array_map( function ( $service_class ) {
            return [
                'namespace' => $service_class,
                'object'    => $this->injector->make( $service_class ),
            ];
        }, $this->services );

        return array_column( $objects, 'object', 'namespace' );
    }

It's a subtle difference - the only actual change here is how the object is instantiated. However, having the flexibility for that change makes an enormous difference.