6 Replies - 843 Views - Last Post: 21 September 2012 - 05:48 PM Rate Topic: -----

#1 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 922
  • View blog
  • Posts: 3,195
  • Joined: 19-January 10

What are interfaces used for (and other conventions questions)

Posted 19 September 2012 - 05:51 PM

So I'm reading up on proper coding conventions so I may make a few topics/bump this one with questions instead of making a new topic for each question. I hope that's okay, if it isn't just say so.

But anyways, I'm reading about interfaces and I'm just wondering, what's the point? All I know about them is that omit an error when it contains a function that isn't in the class it's implemented in.

So why would someone use an interface? What are the benefits?


Also what are the point of namespaces? Should I be using them?


Also here's my current setup/framework for programming. It's probably not exactly the best way of doing things but it's worked so far. I want to know if I'm doing something horribly wrong or not.

File structure:
c/
  index.php
inc/
  autoload.php
  startup.php
  framework.class.php
m/
v/
  css/
    (css files)
  js/
    (javascript files)
  index.php
index.php


/index.php contains:
<?php
  require_once("c/index.php");
  new page();
?>



c/index.php contains:
<?php
class page {
	public function __construct(){
		try {
			require_once('inc/startup.php');
			
			$framework = new framework();
			
			$content = ''; // Predefined to prevent Undefined Variable notices
			if(isset($_GET['pageofprogram__'])){
				$page = preg_replace("[^A-Za-z0-9]", "", $_GET['pageofprogram__']);
			} else {
				$page = "default";
			}
			
			if(file_exists('m/' . $page . '.php')){
				include('m/' . $page . '.php');
			} else {
				include('m/404.php');
			}
			
			include('v/index.php');
			
		} catch (Exception $e){
			echo "There was a problem with the program.<br>Check the exceptions log for more info.";
			file_put_contents("data/errors/exceptions.log", date("Y-m-d H:i:s e") . "\r\n" . print_r($e, true) . "\r\n\r\n", FILE_APPEND);
		}
	}
}
?>



inc/startup.php contains:
<?php
if(!isset($_SESSION)){
	session_start();
}

require_once("autoload.php"); // Autoload so $framework functions work
?>



inc/autoload.php contains:
<?php
function __autoload($class){
	if(file_exists('inc/' . $class . '.class.php')){
		if(!(include('inc/' . $class . '.class.php')) == 'OK'){
			throw new Exception("Could not load class " + $class);
		}
	} else {
		throw new Exception("Could not find class " + $class);
	}
}
?>



inc/framework.class.php contains:
<?php
/*
 * framework.class.php
 * Not exactly a framework, per se, but used to access other classes in a dynamic fashion.
*/
class framework {
	public function get($class){
		if(!isset($this->$class)){
			try {
				$this->$class = new $class();
			} catch(Exception $e){
				/* TODO: ERROR HANDLING */
				die("Fatal error: " + $e->getMessage());
			}
		}
		return $this->$class;
	}
}
?>



As you can see this uses the MVC framework style. Using $framework, I can call any class that is in inc/ using $framework->get('theclass'), and it'll return theclass. This way I don't have to manually include/create them.

This post has been edited by creativecoding: 19 September 2012 - 06:30 PM


Is This A Good Question/Topic? 4
  • +

Replies To: What are interfaces used for (and other conventions questions)

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: What are interfaces used for (and other conventions questions)

Posted 19 September 2012 - 06:45 PM

*
POPULAR

Are you familiar with abstract classes? An abstract class is not instantiable and may contain abstract methods. The abstract methods are required to be implemented in all concrete sucbclasses of the parent class. This ensures that all children adhere to the functionality described in the parent.

An interface is similar, but it allows for polymorphism without strict parent-child inheritance. Think of an interface like a contract. It is up to the implementing class how to fulfill it (or how the methods are implemented), but it must implement those methods. Interfaces are usually adjectives. As an example, Chicken and Watermelon are not directly related via parent-child inheritance. However, they are both edible; and as such, implement the Edible interface.

japanir has a good tutorial on abstract classes vs. interfaces. It's in Java, but it still gets the point across well.
Was This Post Helpful? 6
  • +
  • -

#3 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3637
  • View blog
  • Posts: 5,765
  • Joined: 08-June 10

Re: What are interfaces used for (and other conventions questions)

Posted 19 September 2012 - 07:24 PM

View Postcreativecoding, on 20 September 2012 - 12:51 AM, said:

Also what are the point of namespaces? Should I be using them?

That feature is all about organization.

One of my least favorite things about large PHP systems is how they were forced to name classes and functions before namespaces became available. In order to group together related code, and to prevent different parts of the system from trying to redefine classes and functions with common names, they had to keep adding stuff to the class name. In the end you weren't so much using a class name as you were using a path name.

(Imagine having the entire Java class library defined in the same Java package...)

Just to demonstrate this in a small way, I'll borrow a small example from the Zend Framework docs:
$router = $ctrl->getRouter(); // returns a rewrite router by default
$router->addRoute(
    'user',
    new Zend_Controller_Router_Route('user/:username',
                                     array('controller' => 'user',
                                           'action' => 'info'))
);



In PHP 5.3 that same code could be made far less crude by doing this:
use Zend\Controller\Router\Route;

router = $ctrl->getRouter(); // returns a rewrite router by default
$router->addRoute(
    'user',
    new Route('user/:username',
                  array('controller' => 'user',
                        'action' => 'info'))
);


The use statement takes care of tracing the exact location of the Route class within the system, leaving the code itself far less cluttered.
Was This Post Helpful? 4
  • +
  • -

#4 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 783
  • View blog
  • Posts: 1,664
  • Joined: 30-January 09

Re: What are interfaces used for (and other conventions questions)

Posted 20 September 2012 - 04:28 PM

Namespaces are a handy way to organise your code, as Atli has pointed out. Have a look at this post I made several months back. It demonstrates a use of namespaces where you replicate the namespace in a directory structure as well. This means you can find a filepath in a directory tree according to the namespace of a class. You can then use the spl_autoload_register function to autoload that class on demand.

In terms of interfaces, my usage of them is limited, but I use them when I need every child class to have a certain method defined, but that method differs between those classes. This is different to inheritance from the parent class, because you are not inheriting the method code, you are inheriting only the method name, with the code to be supplied in the extending class. Take this for example:
interface iWorkflow
{
	public function RenderMetrics();
}

abstract class Workflow implements iWorkflow
{
	final public function Approve()
	{
		// Method common to all workflow classes, with the same code for each class
	}

	final public function Reject()
	{
		// Method common to all workflow classes, with the same code for each class
	}

	final public function Submit()
	{
		// Method common to all workflow classes, with the same code for each class
	}
}

class FooWorkflow extends Workflow
{
	final public function ApproveFoo()
	{
		// Method local to FooWorkflow
		// Code snipped
	}

	final public function RejectFoo()
	{
        // Method local to FooWorkflow
	}

	final public function RenderMetrics()
	{
		// Method common to all workflow classes, but has unique executable code for each class

	}
}

class BarWorkflow extends ProjectWorkflow
{
	final public function RenderMetrics()
	{
		// Method common to all workflow classes, but has unique executable code for each class
	}
}


Obviously, this code is heavily stripped back, but you should be able to get the picture. The RenderMetrics() method is intended to be able to be called from any class that extends the Workflow class. One example of why we would want this is when we don't know the class type that has been instantiated, for example:
$workflowClassName = $_GET['WorkflowType'] . 'Workflow';
$myWorkflow = new $workflowClassName;
echo $myWorkflow->RenderMetrics();


Forgiving that fact that the $_GET variable has not been sanitised in any way, you can see how the use of an interface could be handy here. If this RenderMetrics method was not defined, it would not be able to be called. The implementation of an Interface ensures that the developer defines the method. If the interface is implemented and the method is not defined, I believe that references to the class will cause a fatal error. (I could be wrong, it might be a different type of error, but I think it's fatal, haven't got time to check right now).
Was This Post Helpful? 4
  • +
  • -

#5 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 922
  • View blog
  • Posts: 3,195
  • Joined: 19-January 10

Re: What are interfaces used for (and other conventions questions)

Posted 21 September 2012 - 04:01 PM

Thanks for the replies!

So I take it interfaces are a way of making classes which are alike have the "same" functions, so that it's sorta uniform when programming? (IE watermelon class and chicken class both implements edible, and edible requires "eat", because watermelon and chicken both need the ability to be eaten?). Can I get a "real-world" example?

Should I convert to using namespaces? I haven't had any problems with my current setup right now and it looks like the only real use it has is saving a couple of characters by adding a new line, and constantly having to switch around "use" whenever you create a new class.
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10194
  • View blog
  • Posts: 37,646
  • Joined: 27-December 08

Re: What are interfaces used for (and other conventions questions)

Posted 21 September 2012 - 04:15 PM

In Java, there is a Collection interface that defines methods to support the basic insert, remove, contains, and other operations. Implementing classes are all Collections, but they don't have to be related directly. So ArrayList and HashSet are two different classes that both implement the same interface. This allows them to be more appropriately incorporated into the Java Collections framework. If you define your own class that implements Collection, you can use existing API tools with it.

Another good example would be the Observer patter. You can define an Observable interface that multiple, unrelated classes could implement. An Observer interface would be appropriate here as well. It would be a way for objects to notify each other of changes without being related by inheritance.
Was This Post Helpful? 2
  • +
  • -

#7 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 922
  • View blog
  • Posts: 3,195
  • Joined: 19-January 10

Re: What are interfaces used for (and other conventions questions)

Posted 21 September 2012 - 05:48 PM

Ah, I see! Thanks a ton.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1