2013-04-17 52 views
0

我試圖實現類似於存儲庫模式的東西。爲此,我有一個所有Repos實現的接口和一個所有模型擴展的模型基類。如何在接口中使用多態性?

我從PHP

Fatal error: Declaration of MVCBP\Repositories\UserRepository::add() must be compatible with MVCBP\Core\RepositoryInterface::add(MVCBP\Core\Model $model) in D:\wamp\www\mvc\MVCBP\Repositories\UserRepository.php on line 9

以下錯誤消息我想的是,我在倉庫類中的方法應根據接口接受模型的實例作爲參數。不過,我想在實現中鍵入提示特定的模型。這在PHP中可行嗎?

RepositoryInterface.php

<?php 
    namespace MVCBP\Core; 

    use MVCBP\Core\ModelInterface; 

    interface RepositoryInterface 
    { 
    public function add(ModelInterface $model); 
    } 

UserRepository.php

<?php 
namespace MVCBP\Repositories; 

use MVCBP\Core\PDOMySQL; 
use MVCBP\Core\RepositoryInterface; 
use MVCBP\Models\User; 

class UserRepository extends PDOMySQL implements RepositoryInterface 
{ 
    public function add(User $user) 
    { 
     //Omitted 
    } 

    //Omitted 
} 

ModelInterface.php

<?php 
namespace MVCBP\Core; 

interface ModelInterface {} 

user.php的

<?php 
namespace MVCBP\Models; 

use MVCBP\Core\ModelInterface; 
use MVCBP\Core\Validate; 
use MVCBP\Repositories\UserRepository; 

require_once(__DIR__ . '/../lib/password.php'); 

class User implements ModelInterface 
{ 
    //Omitted 
} 
+0

爲什麼你認爲模型是一類? –

回答

0

你可以這樣做。您必須修改您的UserRepository定義。您的add方法只接受MVCBP\Core\Model實例。

UserRepository.php

<?php 
namespace MVCBP\Repositories; 

use MVCBP\Core\PDOMySQL; 
use MVCBP\Core\RepositoryInterface; 

//There was another mistake. Your User class is in MVCBP\Models namespace; 
//use MVCBP\Core\Models\User; -> wrong one 
use MVCBP\Models\User; //correct one 
use MVCBP\Core\Model; 

class UserRepository extends PDOMySQL implements RepositoryInterface 
{ 
    public function add(Model $user) 
    { 
     if (!$user instanceof User) 
      throw new \Exception('Exception msg', 101); //example exception 
     //Omitted 
    } 

    //Omitted 
} 

我更需要一個接口實例即。

public function add(SomeInterface $user) 
{ 
    if (!$user instanceof User) 
     throw new \Exception('Exception msg', 101); //example exception 
} 

class User implements SomeInterface { 
//some code 
} 

然後ReposituryInterface.php看起來是這樣的:

<?php 
namespace MVCBP\Core; 

use MVCBP\Core\Model; 
use MVCBP\Core\SomeInterface; 

interface RepositoryInterface 
{ 
    //We must change method definition so it can take SomeInterface implementation 
    public function add(SomeInterface $model); 
    public function find($id); 
    public function edit(Model $model); 
    public function remove($id); 
    public function all(); 
} 
+0

我編輯了我的代碼來使用接口,但錯誤仍然存​​在。 –

+0

好的。但你是否改變你的RepositoryInterface在add方法中使用接口?我編輯了我的答案併爲RepositoryInterface放置了代碼。你能顯示你的代碼嗎? – Soyale