Tuesday, 17 September 2013

Difference between a function layer and an interface

Difference between a function layer and an interface

What's the difference between doing this:
class UserRepository extends DAO
{
public function GetAllUsers()
{
return $this->Select();
}
public function GetUserById( $id )
{
return $this->Select( $id );
}
}
class MockUserRepository extends MockDAO
{
public function GetAllUsers()
{
return $this->Select();
}
public function GetUserById( $id )
{
return $this->Select( $id );
}
}
class UserController
{
private $userRepository;
function __Construct( $repo )
{
$this->userRepository = $repo;
}
public function ListUsers()
{
$users = $this->userRepository->AnUndeclaredMethod();
// ...
}
}
$repo = new MockUserRepository();
$controller = new UserController( $repo );
and this:
interface IUserRepository
{
public function GetAllUsers();
public function GetUserById( $id );
}
class UserRepository extends DAO implements IUserRepository
{
public function GetAllUsers()
{
return $this->Select();
}
public function GetUserById( $id )
{
return $this->Select( $id );
}
}
class MockUserRepository extends MockDAO implements IUserRepository
{
public function GetAllUsers()
{
return $this->SelectUsers();
}
public function GetUserById( $id )
{
return $this->SelectUsers( $id );
}
}
class UserController
{
private $userRepository;
public function __Construct( IUserRepository $repo )
{
$this->userRepository = $repo;
}
public function ListUsers()
{
$users = $this->userRepository->AnUndeclaredMethod();
// ...
}
}
$repo = new MockUserRepository();
$controller = new UserController( $repo );
If a function was used in the controller that wasn't declared in one of
the repositories, it would throw an error anyway, why is it better to use
an interface for this type of task? What do I benefit from?

No comments:

Post a Comment