Chris Chubb
Chris Chubb

Reputation: 337

PHP Class tree where parent holds instances of the subclasses

I have a master class: "A" with a constructor that takes an optional login and password for a web service. I have subclasses of A: A1, A2 and A3 that have methods for other web services from the same company. They all use the same login and password, but have different uses. Each has it's own set of methods.

So, if I already have an instance of the parent class (or any of the sub-classes), how can I create the other sub-classes without having to reauthenticate the parent class?

What I want to do is like this:

class A {

    protected static $authenticated_service_handle; //Takes a while to set up
    protected $instance_of_A1;

    function __construct($login = null, $password = null) {
        //Go do login and set up
        $authenticated_service_handle = $this->DoLogin($login, $password)

        //HELP HERE: How do I set up $this->instance_of_A1 without having to go through construction and login AGAIN??
        //So someone can call $instance_of_A->instance_of_A1->A1_Specific_function() ?
    }

}

class A1 extends A {

    function __construct($login = null, $password = null) {
        parent::__construct($login, $password);
    }

    public function A1_Specific_function() {
    }

}

//How I want to use it.
$my_A = new A('login', 'password');
$method_results = $my_A->instance_of_A1->A1_Specific_function();
$second_results = $ma_A->instance_of_A2->A2_Specific_function();

Any ideas in how to do this naturally? It seems kind of backwards from standard OO methodology but my calling clients will need to use methods of A1, A2 and A3 at the same time but the number of methods and organization of them lend themselves to breaking into subclasses based on functionality.

Upvotes: 3

Views: 384

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

If the thing you create in your class A is a connection which could be used by all classes that require it, you could use it as such:

class ServiceConnection
{
    private $_authenticated_service_handle; //Takes a while to set up

    function __construct($login = null, $password = null) {
        //Go do login and set up
        $_authenticated_service_handle = $this->DoLogin($login, $password)
    }

    public function DoSomething()
    {
        $_authenticated_service_handle->DoSomething();
    }

}

And pass that connection to all objects that need it:

$connection = new ServiceConnection('login', 'password');

$my_A1 = new A1($connection);
$my_A2 = new A2($connection);
$my_A3 = new A3($connection);

$my_A1->A1_Specific_function();
$my_A2->A2_Specific_function();
$my_A3->A3_Specific_function();

The AN-classes will look like this:

class A1 {

    private $_connection;

    function __construct($connection) {
        $_connection = $connection;
    }

    public function A1_Specific_function() {
        $_connection->doSomething();
    }

}

Upvotes: 3

Related Questions