Jump to content

Recommended Posts

interface DoesSomething
{
    public function doSomething ();
}

class Foo
{
    public function bar (DoesSomething $obj)
    {
        $obj->doSomething();
    }
}

 

It assures that $obj conforms to the interface of DoesSomething; if it didn't - it may not have the method doSomething() which could have catastophic results compared to the light-weight error received for not implementing the interface.

Interfaces are an extremely useful tool when you have multiple people working on a project and you want to make sure that everyone is adhering to the same coding goals and procedure. This is only one example of a valid usage for them, but a pretty solid one nonetheless. If I can provide you with an interface that X number of classes you write must follow, I can go ahead and start writing the supporting pages knowing exactly how they will interact with your code once it's handed over.

So it is just to ensure that other people (and yourself) will adhere to however you want the class to be and not really anything else?

 

Here is a somewhat practical example using interfaces:  You can see that the following code would be impossible in strongly typed languages (i.e., Java) and impractical in loosely types languages (PHP):

 

<?php
interface DataEntityFactory
{
public function buildEntity($row);
}

class DogEntityFactory implements DataEntityFactory
{
public function buildEntity($row)
{
	$dog = new Dog();

	$dog->setId($row['id']);
	$dog->setName($row['name']);

	return $dog;
}
}

class CatEntityFactory implements DataEntityFactory
{
public function buildEntity($row)
{
	$cat = new Cat();

	$cat->setId($row['id']);
	$cat->setName($row['name']);

	return $cat;
}
}

class DataMapper
{
function mapData($rs, $factory)
{
	$entities = array();

	foreach($rs as $row){
		$entities[] = $factory->buildEntitiy($row);
	}

	return $entities;
}
}

$dogs = DataMapper::mapData(DBAbstractionClass(GET_ALL_DOGS_SQL), new DogEntittyFactory());
$cats = DataMapper::mapData(DBAbstractionClass(GET_ALL_CATS_SQL), new CatEntittyFactory());

?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.