1

I have a collection of view objects. Each one of these objects must 100% implement the following interface:

/**
 * Interface that each base ViewBlock object must implement.
 */
interface ViewBlockInterface extends CosmeticInformationInterface, ScriptInterface
{

    public function getBlockName();
}

Now, here's 2 interfaces that some of these objects might choose to implement:

use Interfaces\StyleInterface;
use TemplateInterface;

As such, an object must be of type ViewBlockInterface but can be either StyleInterface or TemplateInterface or both, meaning that we can potentially have a case where an object is all 3 at the same time.

Here's my problem: in my generator (that ingests all these objects), I have no clean way of handling each interface. I have to rely on code like:

if( $object instanceof ScriptInterface) {
    //Do some stuff that should only happen if this check passes.
}
..
..
//Do the same thing for N interfaces

Is there no pattern, way of architecturing my objects to escape this?

I can re-write this any way I want without a problem.

4
  • 1
    Why not implement the logic that you do inside the if conditions inside the objects instead? – Did Jan 9 '20 at 9:07
  • Just add another method function execute() in the interface that requires to implement the logic in the clients and then in your generator you just call ...->execute(); – Did Jan 9 '20 at 9:10
  • Can you add the other interfaces as well? And how are these objects going to get used? What are the purposes of each interface? – Greg Burghardt Jun 7 '20 at 13:08
  • Your issue could perhaps be solved by the Visitor design pattern. This however depends on the functionality you're after. – Andy Jun 8 '20 at 5:59
0

Interfaces actually behaves like abstract methods and constants. So, there is no other way of not calling the object from implemented interface in that class. You may have seen that methods are public in interface. The class that implements the interfaces must define all the methods that they inherit from the interfaces.

1
  • 1
    How can an interface behave like a constant? A constant is data. – Greg Burghardt Jan 9 '20 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.