Hello

I'm building a factory for my DAO's and want it to return the correct DAO based on the class of the ValueObject passed to the factory.

Now, if this was java I would use something like this:

if (valueObject instanceof User) {
    return new UserDAO();
} else if (valueObject instanceof Profile) {
    return new ProfileDAO();
}

or even better: overload my factory method :) But overloading can't be done that way in PHP.

But as far as I know the instanceof function isn't included in PHP5.

Any idea of an elegant way to do this?

-Vidaj-

Again I find myself amazed how smoothly things can be done in PHP.

I found out that I didn't need to use the instanceof after all. I created my factory in a dynamic and reusable way, without specific testing for each class.

I'll include it here in case someone has any comments on it, or someone else needs something like it:

class DAOFactory {
	
	private $daos = array();
	
	private static $instance;
	
	protected  function __construct() {
		
	}
	
	public static function getInstance() {
		if (!isset(self::$instance)) {
			self::$instance = new DAOFactory();
		}
		return self::$instance;
	}
	
	public function addDAO($valueObjectName, $daoName) {
		$this->daos[$valueObjectName] = $daoName;
	}
	
	public function getDAO($valueObject) {
		/* Get the classname of the ValueObject. */
		$className = get_class($valueObject);
		
		/* Check if the DAO is registered. */
		if (isset($this->daos[$className])) {
			
			/* Get the class name of the DAO. */
			$dao = $this->daos[$className];
			
			/* Include the class-file if needed. */
			require_once($dao . ".class.php");
			
			/* Create a new instance of the DAO. */
			return new $dao();
		}
		
		/* DAO isn't registered. */
		return false;
	}
	
}

Note: It requires that every file is named Classname.class.php

To use it:
Case - You have a ValueObject User and a UserDAO

DAOFactory::getInstance()->addDAO("User", "UserDAO");

$user = new User();
$dao = DAOFactory::getInstance()->getDAO($user);
This article has been dead for over six months. Start a new discussion instead.