How to apply interfaces and abstraction in PHP - php

So I have understood how interfaces and abstraction work in PHP, I just don't see the point for example, of having a interface if it just sets a guide and requires implemented objects to have certain methods. Especially since the interface is not even getting instantiated.
This also goes with abstraction, I just can't apply it to my code and see it as such a great thing. When I am trying to create objects on a bigger scale to interact with each other in order to figure out interfaces, each class ends up passing information back and forth, but never is the interface touched.
So what I'm asking is if you guys have any advice or links to outside sources that is good at explaining this kind of thing.

Here's one simple example. Creating interfaces and abstract classes allows you to ensure an object adhears to a common API. See the example below.
interface iCar
{
function drive();
}
abstract class Car implements iCar
{
public $make = 'Generic';
public function drive()
{
printf("I'm driving in my %s%s", $this->make, PHP_EOL);
}
}
class FordTruck extends Car
{
public $make = "Ford";
}
class Porsche extends Car
{
public $make = 'Porsche';
public function drive()
{
printf("I'm speeding around in my %s%s", $this->make, PHP_EOL);
}
}
class Yugo extends Car
{
public $make = 'Yugo';
public function drive()
{
printf("I'm pushing my %s around town%s", $this->make, PHP_EOL);
}
}
function drive(iCar $car)
{
$car->drive();
}
$car1 = new FordTruck;
$car2 = new Porsche;
$car3 = new Yugo;
drive($car1);
drive($car2);
drive($car3);
Even if you don't specify the type of input parameter on the drive() function, you can check if the input is an instanceof an iCar
function drive($car)
{
if ($car instanceof iCar)
$car->drive();
}
Another example would be building a caching interface in your application. You can specify that all cache engines support the same methods for reading/writing/invalidating objects in the cache without knowing (or caring) about the actual implementation of a particular cache engine.

I could give you the simplest as possible example.
Assume you want a feature that allow your site to login with Facebook/Twitter
# here's your interface/abstract class
interface Auth_Adapter {
public function auth();
}
# now your Facebook
class Auth_Adapter_Facebook implements Auth_Adapter {
public function login() {
# include facebook-sdk and auth
}
}
# Twitter
class Auth_Adapter_Twitter implements Auth_Adapter {
public function login() {
# include twitter-oauth and auth
}
}
Imagine when someone try to use Facebook/Twitter thing They can simply call
$adapter = new Auth_Adapter_Facebook;
$adapter->login();
$adapter = new Auth_Adapter_Twitter;
$adapter->login();
As you can see both adapters use the same login interface. What's happen if in the future you have to include 'Pinterest' login? Your code still work as long as you implement the same interface.
EDIT: More explanations
Here's the reason why you have to use interface or abstract
# I use `type-hinting` here. So I can ensure that only object that implements `Auth_Adapter` will allow. Without this implementation someone might pass some other object that doesn't have `login` method in. But in our case we don't have to worry about that.
public function perform_login(Auth_Adapter $adapter) {
$adapter->login();
}

Related

Is it good practice to create a factory implementation which uses other factories to build the final concrete object?

In an application I'm building there's a CLI entry point class:
class CLIEntryPoint {
protected $factory;
public function __construct(ApplicationObjectFactoryInterface $factory) {
$this->factory = $factory;
}
public function run(...$args) {
$choice = $args[1];
$appObject = $this->factory->makeApplicationObject($choice);
$appObject->doApplicationRelatedStuff();
}
}
This entry point is created using Dependency Injection in my "front controller" script and it receives an ApplicationObjectFactoryInterface implementation (actually the current implementation of ApplicationObjectFactoryInterface is injected by the DI container, which in turn reads it from its configuration file, but that's not the point).
The current implementation of ApplicationObjectFactoryInterface also uses DI and depends on other factories which help it building the resulting application object:
class CurrentImplementationOfApplicationObjectFactory implements ApplicationObjectFactoryInterface {
protected $someComponentFactory;
protected $anotherComponentFactory;
public function __construct(SomeComponentFactoryInterface $someComponentFactory, AnotherComponentFactoryInterface $anotherComponentFactory) {
$this->someComponentFactory = $someComponentFactory;
$this->anotherComponentFactory = $anotherComponentFactory;
}
/**
* Interface's method
*
* #return ApplicationObjectInterface
*/
public function makeApplicationObject($choice) {
$component = $this->someComponentFactory->makeSomeComponent();
$anotherComponent = $this->anotherComponent->makeAnotherComponent();
switch ($choice) {
case 1:
return new CurrentImplementationOfApplicationObject1($component, $anotherComponent);
case 2:
return new CurrentImplementationOfApplicationObject2($component, $anotherComponent);
default:
return new DefaultImplementationOfApplicationObject($component, $anotherComponent);
}
}
}
Here CurrentImplementationOfApplicationObject1, CurrentImplementationOfApplicationObject2 and DefaultImplementationOfApplicationObject all implement the ApplicationObjectInterface interface and therefore they all have the doApplicationRelatedStuff method.
I would like to know whether it's good practice or not to write code like I did and if not how can I improve it.
Basically here I am creating a component which depends on other components in order to function properly using a factory which in turn needs inner factories to build the component which implements the ApplicationObjectInterface interface.
Is it considered good practice?
Thanks for the attention, as always!
EDIT: I looked at the article of Steven and tried to refactor CLIEntryPoint. The only problem now seems to be how to pass the $choice parameter to the factory which now is inside of the proxy when the run() method is called. Is this code structure better than the one I posted above? Of course, SomeComponentFactoryInterface and AnotherComponentFactoryInterface should follow the same behaviour (the factory that uses them should not use them directly, but through two proxies which implement, in order, SomeComponentInterface and AnotherComponentInterface). I hope I get it right, anyway, here is the code:
class CLIEntryPoint {
protected $applicationObject;
public function __construct(ApplicationObjectInterface $applicationObject) {
$this->applicationObject = $applicationObject;
}
public function run(...$args) {
$choice = $args[1]; // How do I deal with different choices when I am using a Proxy? I should have different application objects depending on input.
$this->applicationObject->doApplicationRelatedStuff();
}
}
interface ApplicationObjectInterface {
public function doApplicationRelatedStuff();
}
class ApplicationObjectProxy implements ApplicationObjectInterface {
protected $applicationObjectFactory;
protected $applicationObjectImplementation = NULL;
public function __construct(ApplicationObjectFactoryInterface $factory) {
$this->applicationObjectFactory = $factory;
}
public function __call($method, $args) {
// Calling interface's
$implementation = $this->getImplementation();
$methodOfInterfaceToCall = preg_replace('/Proxy$/', '', $method);
return $implementation->{$methodOfInterfaceToCall}(...$args);
}
/**
* Laxy loading method.
*/
protected function getImplementation() {
if (is_null($this->applicationObjectImplementation)) {
$this->applicationObjectImplementation = $this->applicationObjectFactory->makeApplicationObject(); // Choice should go here somehow...
}
return $this->applicationObjectImplementation;
}
public function doApplicationRelatedStuff() {
// This will call the PHP's magic `__call` method, which in turn will forward the call to the application object's
// implementation returned by the factory.
return $this->doApplicationRelatedStuffProxy();
}
}
Actually yes, this is a pattern called the Abstract Factory Pattern. So an example that I used to present it in front of my class during my undergrad:
So if you are building a video game first person shooter, you might want to create three concrete factories like:
FlyingMonsterFactory
SwimmingMonsterFactory
WalkingMonsterFactory.
All these factories would implement an abstract MonsterFactory.
With this, you can have your video game create a level in which you want waves of the same type of monsters, so you can have a randomWaveMonsterGenerator method return a MonsterFactory which might have returned a concrete SwimmingMonsterFactory. So then you will have a wave of SwimmingMonster(s) generated by the SwimmingMonsterFactory.
So answer your description more directly, looking at your code above, you asked the question on choice for Dependency Injection. With Dependency Injection, I believe for this type of pattern, you will have to inject every concrete class before your code even attempts to get the implementation class.
So for example:
Your code above says the run method gives an argument called
choice.
With this choice, you will have to use it as a parameter into a getImplementation method.
All the concrete objects that the getImplementation method that rely upon Dependency
Injection have to be created BEFORE you call the getImplementation method.
But since you don't know which implementation class will be called, I believe you have to inject ALL the implementation classes before hand.
Then you can use the choice variable as a parameter to get the correct implemented factory class.
Hope this helps!

PHP Factory design pattern method clarification

I want to know if this tutorial is correctly implementing factory design pattern in PHP. Below is the actual source code.
<?php
class Automobile
{
private $vehicle_make;
private $vehicle_model;
public function __construct($make, $model)
{
$this->vehicle_make = $make;
$this->vehicle_model = $model;
}
public function get_make_and_model()
{
return $this->vehicle_make . ' ' . $this->vehicle_model;
}
}
class AutomobileFactory
{
public static function create($make, $model)
{
return new Automobile($make, $model);
}
}
// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');
print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron"
According to a book "Design Patterns" by Gang of Four, applicability of factory pattern is
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the objects it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate
First point, this example actually knows what class of objects to create, which is Automobile, doesn't it?
Second point, there is no subclass. Automobile class does not inherit from AutomobileFactory. I thought AutomobileFactory should have at least one function implemented by Automobile, which deals with object creations.
Can someone clarify this? I just started learning design patterns, and every time I encounter tutorials different from others, it confuses me a lot.
I pretty much agree with what is said in Wikipedia
The creation of an object precludes its reuse without significant duplication of code.
The creation of an object requires access to information or resources that should not be contained within the composing class.
The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
The main reason I create factories is this one I highlighted.
For example, let's imagine a real world factory with many plants throughout the country. This factory produces doors. Doors needs knobs. For logistics reasons, each one of the plants of the factory has its own knob suppliers, another completely different factory.
The production manager software of this factory will choose based on some criteria which plant will produce a lot of doors, but it does not need to know from where the knobs will come. The chosen plant will ask for its own supplier for a knob for the produced door.
However, for the client, it does not matter which plant made the door, he only cares about having his door.
Let's put this on code:
class Knob {
// something...
}
interface KnobSupplier {
public function makeKnob();
}
class SaoPauloKnobSupplier {
public function makeKnob() {
return new Knob('Knob made in São Paulo');
}
}
class NewYorkKnobSupplier {
public function makeKnob() {
return new Knob('Knob made in New York');
}
}
class Door {
public function __construct(Knob $knob) {
// something...
}
}
interface DoorFactory {
public function makeDoor();
}
class SaoPauloDoorFactory {
private $knobSupplier;
public function __construct() {
$this->knobSupplier = new SaoPauloKnobSupplier();
}
public function makeDoor() {
return new Door($this->knobSupplier->makeKnob(), "Door made in São Paulo");
}
}
class NewYorkDoorFactory {
private $knobSupplier;
public function __construct() {
$this->knobSupplier = new NewYorkKnobSupplier();
}
public function makeDoor() {
return new Door($this->knobSupplier->makeKnob(), "Door made in New York");
}
}
class ProductionManager {
private $plants = array();
// methods for adding plants, etc...
public function getDoor() {
// Somehow decides which plant will create the door.
return $plant->makeDoor();
}
}
class Client {
public function getMyDoor(ProductionManager $manager) {
return $manager->getDoor();
}
}
Using this code like:
$manager = new ProductManager();
$manager->addPlant(new SaoPauloDoorFactory());
$manager->addPlant(new NewYorkDoorFactory());
$client = new Client();
var_dump($client->getMyDoor($manager));
ProductManager does not know anything about knobs, Client does not know anything about the factory having more than one plant.
I don't really like the tutorial. As you can see in the WikiPedia page about factories ( https://en.wikipedia.org/wiki/Factory_pattern ) - it's normally done differently. The WikiPedia example does comply with the rules you mention. Check out the PHP section there.
I'm with you kidonchu, I don't really see that example as a traditional factory method pattern.
I would write your example like this (psuedo code)
<?php
abstract class CarAbstract
{
protected $_vehicleMake;
protected $_vehicleModel;
public function __construct($model)
{
$this->_vehicleModel = $model;
}
public function getMakeAndModel()
{
return $this->_vehicleMake . ' ' . $this->_vehicleModel;
}
}
class Bugatti extends CarAbstract
{
public function __construct($model)
{
parent::__construct($model);
$this->_vehicleMake = get_class($this);
}
}
class AutomobileFactory
{
public static function getInstance($make, $model)
{
if (is_file('Model/Car/' . $make . '.php')){
require_once 'Model/Car/' . $make . '.php';
$car = new $make($model);
}else{
throw new Exception('Car not found');
}
}
}
$veyron = AutomobileFactory::getInstance('Bugatti', 'Veyron');
print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
There's actually a single Factory Method design pattern following the original gang of four catalog. The Abstract Factory is wholly different and is based on different structural assumptions. The Simple Factory is not a design pattern, but the what Freemans call a 'programming idiom.' The Factory method includes an abstract Creator and Product, and the Clients generally make their requests through the Creator. Specific factories are found in the ConcreteCreator(s) and the concrete products are child classes of the Product class and are instantiated by concrete creators. For a complete and simple PHP example see http://www.php5dp.com/a-simple-php-design-pattern-the-factory-method/.

Avoid object multiple inheritance

I'm creating a form generator and i'm actually working on an specific element : DuplicableElement.
The form can contains a special container (DuplicableContainer) that used jQuery plugin (sheepit) to duplicate itself.
To get working this, the DuplicatableContainer can only have DuplicableElement in its child because they are a lot of things specific to them.
The problem is that php does not allow multiple inheritance. (should works with php "Traits" but not supported actually). I can't make a DuplicableTextBox extends simultaneously DuplicableFormElement and the normal TextBox element.
I hope i was enough clear.
Edit: Even with "Traits", the problem still exists, and i can't find a clean solution.
You can also inject behaviors/plugins into your elements providing the functionality of traits but without official support.
<?php
class Car {
public $behaviors = array();
public function __call($method, $params) {
foreach($this->behaviors as $behavior) {
if (method_exists($behavior, $method)) {
return call_user_func_array(array($behavior, $method), $params);
}
}
}
}
class Engine {
public function start() { echo 'Started'; }
}
$car = new Car;
$engine = new Engine;
$car->behaviors[] = $engine;
$car->start(); // Started
Do the DuplicableElements specifically need to be a class? If the public interface to the object is what matters, you could make DuplicableElement an interface instead. A class can extend one class and implement multiple interfaces all at once.

How to structure several PHP classes

I'm wondering if anyone could give me a suggestion for to best handle this situation:
I have several systems from which to pull data to display on a single PHP-driven website. The type of information will be the same across systems (contacts, addresses, etc) but the way I pull data (MS-SQL, XML, REST) will not.
I want to create a class, or set of classes, for each of the connection types and use simple methods such as getContact(), getAddress(), etc. I am wondering how best to structure this.
The most obvious way that comes to mind means creating classes for each connection type, like:
class.sys_mysql.php. class.sys_xml.php, etc
But then won't I be duplicating the methods in each class? Maybe that's OK, but I'm curious if there's a better way, as far as future maintenance goes.
Maybe I should simply isolate the queries/data extraction methods, into separate class files? Classes within classes? Extended classes? I'm less familiar with these.
Any advice would be greatly appreciated.
DC
--------- more info ----------
Hi all. I really appreciate all the great advice. Not to belabor this thread but I'm still a bit confused on how I should break things down. I will try and be a bit more specific:
Basically, I have 3 (more in the future) offices, from which one PHP website pulls information. Each office uses a different CRM, and a different system for interfacing with that CRM. One uses MSSQL, another XML requests, etc.
Each office wants to display information similarly on the website, but there are minor differences. There may be more differences in the future. However, there are by far more similarities, and so I want to capitalize on higher level functions like getContacts($id) which are shared between them.
I am trying to write these classes so I can:
1) use higher level methods to pull data easily
2) account for different ways of pulling data (xml,sql,etc)
3) account for differences between how data is displayed on the website (office 1, office 2, office 3)
4) manage the connection credentials for each office and allow for expandability_
5) I should also mention that I will be creating separate classes for reporting, sending out automated e-mails, calculating finances...separate modules that will need to use existing classes to pull data.
I realize that some of the examples here see to cover 1 and 2, but I am confused as to how to get 3, 4 and 5 working with 1 and 2.
I really appreciate the help.
DC
This is what Interfaces are for.
You define the methods required to interact with the data in an Interface, and then you create classes that implement that Interface
If some of the systems have similar access models (i.e. perhaps two different DB Servers, but both are accessed using PDO) you could abstract it further and put the "low level" functionality into service-specific classes (which implement an Interface) and then a higher-level class which defines the actual methods you use.
Another option is that you could put the "common" methods (those that are identical or can be made idetntical with service-type checks) into a base class, which all others extend.
Example for option one:
interface DataModel {
public function findContacts($search);
public function getContact($id);
public function findAddresses($search);
public function getAddress($id);
}
class XMLDataModel implements DataModel {
public function findContacts($search) {
...
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
class RESTDataModel implements DataModel {
public function findContacts($search) {
...
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
As you can see, you simply define an Interface, which specifies which methods a class must implement.
If you had two very similar classes, perhaps one for MySQL and one for PostreSQL, and you can't/don't want to combine them into a single PDO class, you could do the following:
class PDODataModel implements DataModel {
private $model;
public function __construct ($serverType) {
if ($serverType === 'mysql') {
$this->model = new MySQLPDODataModel();
}
elseif ($serverType === 'postgresql') {
$this->model = new PostgresQLPDODataModel();
}
}
public function findContacts($search) {
// common logic about $search, perhaps checking it's a valid search?
$result = $this->model->searchForContacts($search);
// more common logic, maybe higher level filtering..
return $result;
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
interface PDODataModelDriver {
public function searchForContacts($search);
}
class MySQLPDODataModel extends PDODataModel implements PDODataModelDriver {
public function searchForContacts($search) {
// MySQL-specific query to search for contacts
}
}
class PostgresSQLPDODataModel extends PDODataModel implements PDODataModelDriver {
public function searchForContacts($search) {
// PostgreSQL-specific query to search for contacts
}
}
The other option I mentioned was to work in the opposite direction:
abstract class PDODataModel implements DataModel {
protected $pdo;
protected $dsn;
public function __construct () {
$this->pdo = new PDO($this->dsn);
}
public function findContacts($search) {
// common logic about $search, perhaps checking it's a valid search?
$result = $this->searchForContacts($search);
// more common logic, maybe higher level filtering..
return $result;
}
public function getContact($id) {
...
}
public function findAddresses($search) {
...
}
public function getAddress($id) {
...
}
}
class MySQLPDODataModel extends PDODataModel {
protected $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
protected function searchForContacts($search) {
// MySQL-specific query to search for contacts
}
}
class PostgresSQLPDODataModel extends PDODataModel {
protected $dsn = 'pgsql:host=localhost;port=5432;dbname=testdb';
protected function searchForContacts($search) {
// PostgreSQL-specific query to search for contacts
}
}
This is a classical example of a strategy design patter. Your first mind was absolutely fine, but if you're repeating yourself in each class you should consider creation of a abstract class that will handle the common code.
So it could look like this:
$myService = new MyService(new XMLReader('/path/to/file'));
echo $myService->getContanct('abc')->getName();
And skeleton of your classes:
class MyService {
private $reader;
public function __construct(ReaderInterface $reader) {
$this->reader = $reader;
}
// ...
public function getContacnt($id) {
$contact = $this->reader->getContact($id);
// do some extra stuff here
return $contact;
}
}
interface ReaderInterface {
public function getContanct($id);
public function getAddress($id);
}
abstract class AbstractReader implements ReaderInterface {
protected $loaded = false;
protected $data = array();
abstract protected function load();
public function getContanct($id) {
if ($this->loaded == false) {
$this->load();
$this->loaded = true;
}
return $this->data['contact'][$id];
}
}
class XMLReader extends AbstractReader {
public function __construct($filepath) {
...
}
protected function load() {
...
foreach (...) {
$this->data[...] = ...;
}
}
}
class MSSQLReader extends AbstractReader {
public function __construct(PDO $dbh) {
...
}
protected function load() {
...
while ($row = $stmt->fetchRow()) {
$this->data[...] = ...;
}
}
}
EDIT (2011-03-07) - According to your comment.
PHP supports variable variables (new $type()) but never use this! It's a horrible, and if overused make code really crappy.
This is a yet another example of a "classical issue". Use a factory pattern (depending on the complexion of the creation you might want to use more abstract variety of this pattern - abstract factory
When you need to dynamically determine class name (eg. from variable) use reflection API to instate an object.
You should create an object-storage mapping layer for each data source, which instantiates the objects into storage agnostic model objects. See http://martinfowler.com/eaaCatalog/dataMapper.html
If you have control over the structure of your data formats, I suggest you serialize your data in a consistent way (especially in XML) and provide drivers for each data format.
For instance, every driver will have 'findAll', 'getOne', 'count', etc. methods. The driver can be given a model to populate with the retrieved data.
abstract class DataDriver {
function __construct($model) {}
abstract public function findAll();
abstract public function getOne();
abstract public function count();
// ...
}
class XMLDriver extends DataDriver {
// implements all the methods
}
class SQLDriver extends DataDriver {
// implements all the methods
}
class Contact {
public var $firstName;
public var $lastName;
function getFullName() {
return trim($this->firstName . ' ' . $this->lastName);
}
}
$accessor = new SQLDriver('Contact');
$contacts = $accessor->findAll();
If your data will be serialized in an uncontrolled manner, the approach you suggest is the best. Just make sure to separate your models (e.g. Address book, Contact) from the method of retrieval (eg. get_address_book_xml, get_address_book_sql, etc.)
Of course there are many ways of separating your models from your data-mapping driver. The importance is you find the solution that works best for you given that you're using such different formats.

Type Hinting For Multiple Unrelated Interfaces

Is there a way in php to type hint for two different, unrelated interfaces? For example:
interface errorable {
function error($msg);
}
interface recordable {
ssh_for_recorder();
}
class uploader__module extends base__module implements errorable, recordable {
public function ssh_for_recorder() {
return new ssh2;
}
public function error($msg) {
$this->errors[] = $msg;
}
public function upload() {
$recorder = new recorder($this);
$recorder->run();
}
}
class recorder {
private $ssh2;
private $module;
private function upload() {
if (!$this->ssh2) {
$this->module->error("No SSH2 connection");
}
}
public function __construct({recordable,errorable} $module) {
$this->module = $module;
$this->ssh2 = $module->ssh_for_recorder();
}
}
As you can see in the above code, the recorder class expects its module to have the ability to run both error() and ssh_for_recorder(), but these are defined by different interfaces. errorable need not be recordable and vice versa either.
Is there a best practice for doing this? I was thinking of creating an interface that extends from recordable and errorable and having upload__module implement that, but I don't know what to call it.
No, this is not possible in php.
There are other languages (mostly functional) that support this feature which is called a union type ( http://en.wikipedia.org/wiki/Sum_type ).
The only hack within PHP is a helper function to do the checks for you within the method like so:
function CheckInterfaces($object,array $interfaces)
{
foreach($interfaces as $i)
{
if(!is_a($object,$i))
{
return false;
}
}
return true;
}
And then within the method do:
public function Something($object)
{
if(CheckInterfaces($object,array("foo","bar")))
{
throw new ArgumentException(gat_class($object) . " Must be a member of foo,bar to be passed to Something");
}
}
another method around this issue ius to create a union interface for your required interfaces, heres quick example
interface foobar extends foo,bar{}
then you can just require foobar for the method.
I've decided to answer this question even though you've already accepted an answer on the grounds that none of the given answers are really acceptable. While the accepted answer is technically correct, there is a way getting around it. As for the other answers, their workarounds are inelegant and not entirely satisfactory.
PHP supports a fairly obscure feature that allows one interface to inherit from another, and in fact an interface is capable of inheriting from multiple base interfaces.
For example, the following is perfectly valid:
interface iFoo
{
public function doFoo ();
}
interface iBar
{
public function doBar ();
}
interface iBaz extends iFoo, iBar
{
// This interface implicitly has all the methods of iFoo and iBar
}
Semantically, if you want a method/function to only accept an argument that implements multiple interfaces then that would tend to suggest that you expect that classes that implement the same set of multiple interfaces should in fact be implementing an interface that covers both the interfaces you want your argument to conform to.
In your case if you want something that is both a errorable and a recordable then you simply need to add the following interface:
interface RecordableErrorable extends Recordable, Errorable { }
And then the constructor for your Recorder class would simply expect that interface as its argument.
public function __construct(RecordableErrorable $module) { }
One possible sticking point could be if Recordable and Errorable both implement methods with the same name. There would be a clash there that would need resolving. I do believe there are mechanisms in PHP for handling that case, though I couldn't tell you what they are.
public function __construct(recordable $recordable_module, errorable $errorable_module) {
if($recordable_module == $errorable_module){
$module = $recordable_module;
}
$this->module = $module;
$this->ssh2 = $module->ssh_for_recorder();
}

Categories