vendredi 28 octobre 2016

PHP - Using Interfaces, Strategy Pattern and Optional Method Parameters

I was wondering if i could get a bit of help.

I have an interface like so

interface BackupContract {
    public function testConn($request, $port);
}

Then the 2 example implementations of this interface is as follows

class FTPBackup implements BackupContract {
    public function testConn($request, $port = 21) {
        // code here
    }
}

class SFTPBackup implements BackupContract {
    public function testConn($request, $port = 22) {
        // code here
    }
}

As i need things like 'service' and port designated at runtime, im using 'strategy pattern' to achieve this, like so.

class BackupStrategy {
    private $strategy = NULL;

    public function __construct($service) {

        switch ($service) {
            case "ftp":
                $this->strategy = new FTPBackup();
                break;
            case "sftp":
                $this->strategy = new SFTPBackup();
                break;
        }

    }

    public function testConn($request, $port)
    {
        return $this->strategy->testConn($request, $port);
    }
}

and finally, in my controller im using the following code to put it all together.

$service = new BackupStrategy($request->input('service'));
$service->testConnection($request, $request->input('port'));

The problem is, that if a user doesnt enter a port, it is meant to auto assign a port variable, i.e 21 or 22 like in the 2 implementations.

It doesn't seem to be working, but its not throwing any errors



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire